How to Get First Row of Pandas DataFrame?

How to Get First Row of Pandas DataFrame?

To get the first row of a pandas DataFrame, you can use the iloc or loc attribute. Here's how to do it:

  • Using iloc:

The iloc attribute is primarily integer-location based indexing. To get the first row:

import pandas as pd # Sample data df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }) first_row = df.iloc[0] print(first_row) 
  • Using loc:

The loc attribute is label-based indexing. If you have a default integer index, the first row can be accessed in the following way:

first_row = df.loc[0] print(first_row) 

Both of these methods will return the first row as a pandas Series. If you want to keep it as a DataFrame:

first_row_df = df.iloc[[0]] print(first_row_df) 

Note the double square brackets [[0]], which ensure that the result is a DataFrame, not a Series.


More Tags

logging control-panel viewport cardlayout jquery-plugins nohup filestructure splitter web3js guava

More Programming Guides

Other Guides

More Programming Examples