Get a specific row in a given Pandas DataFrame

Get a specific row in a given Pandas DataFrame

To get a specific row in a given Pandas DataFrame, you can use the .iloc[] (by integer location) or .loc[] (by label) accessor.

Here's a quick guide on how to do this:

Using .iloc[]:

If you know the integer index of the row you want, you can use the .iloc[] accessor.

Example:

import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }) # Get the row at index 1 row = df.iloc[1] print(row) 

This will output:

A 2 B 5 C 8 Name: 1, dtype: int64 

Using .loc[]:

If you have a custom index for your DataFrame and you know the label of the row you want, you can use the .loc[] accessor.

Example:

import pandas as pd # Sample DataFrame with custom index df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }, index=['x', 'y', 'z']) # Get the row with label 'y' row = df.loc['y'] print(row) 

This will output:

A 2 B 5 C 8 Name: y, dtype: int64 

Note:

Both .iloc[] and .loc[] return a Pandas Series representing the row. If you need to retain the DataFrame format for the row, you can use slicing:

For .iloc[]:

row_df = df.iloc[[1]] 

For .loc[]:

row_df = df.loc[['y']] 

This will give you a one-row DataFrame instead of a Series.


More Tags

mongoose ms-project flutter-image rank executable-jar pageload java-http-client android-ndk django-admin pipenv

More Programming Guides

Other Guides

More Programming Examples