Thursday 21 September 2023

Pandas: Understanding the Dataframe index attribute

Dataframe index attribute specifies the index labels assigned to each row.

dataframe_index.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)

Output

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

The index attribute (df.index) returns a RangeIndex object, which represents the range of index labels from the start value (0) to the stop value (6) with a step of 1.

 

We can traverse the elements of DataFrame using RangeIndex.

 

range_index.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

In the above example, for loop iterates over the DataFrame RangeIndex. Inside the loop, df.loc[index_label] is used to access each row of the DataFrame by its index label index_label.


Previous                                                 Next                                                 Home

No comments:

Post a Comment