Sunday, 24 September 2023

Pandas: DataFrame: Access each row by its index label

‘df.loc[i]’ is used to access each row of the DataFrame by its index label i

 

Example

index_labels = df.index
for index_label in index_labels:
    row = df.loc[index_label]

 access_dataframe_row_by_label.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Ram', 'Joel', 'Gopi', 'Jitendra', "Raj"],
        'Age': [34, 25, 29, 41, 52, 23],
        'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai']}

df = pd.DataFrame(data)

# Access the index attribute
index_labels = df.index
print(index_labels)

print("\nTaverse the dataframe using RangIndex")
for index_label in index_labels:
    row = df.loc[index_label]
    print(row, "\n")

Output

RangeIndex(start=0, stop=6, step=1)

Taverse the dataframe using RangIndex
Name      Krishna
Age            34
City    Bangalore
Name: 0, dtype: object 

Name        Ram
Age          25
City    Chennai
Name: 1, dtype: object 

Name         Joel
Age            29
City    Hyderabad
Name: 2, dtype: object 

Name         Gopi
Age            41
City    Hyderabad
Name: 3, dtype: object 

Name     Jitendra
Age            52
City    Bangalore
Name: 4, dtype: object 

Name        Raj
Age          23
City    Chennai
Name: 5, dtype: object

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment