Sunday 1 October 2023

How to Get a List of the Axes of a Pandas DataFrame

DataFrame axes attribute returns a list of the axes objects used by the DataFrame, where the first element specifies the row index and the second element specifies the column index.

 

Example

axes = df.axes
row_axes = axes[0]
column_axes = axes[1]

 

Find the below working application.

 

dataframe_axes.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)
axes = df.axes

row_axes = axes[0]
column_axes = axes[1]

# Traverse the DataFrame rows
print("Traverse data frame by rows")
for row_index in row_axes:
    print(df.iloc[row_index])

# Traverse the DataFrame using index and column access
print("\nTraverse the DataFrame using index and column access")
for i in range(len(df)):
    row = df.iloc[i]
    for column in column_axes:
        print(column, " : ", row[column])
    print("\n")

 

Output

Traverse data frame by rows
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

Traverse the DataFrame using index and column access
Name  :  Krishna
Age  :  34
City  :  Bangalore


Name  :  Ram
Age  :  25
City  :  Chennai


Name  :  Joel
Age  :  29
City  :  Hyderabad


Name  :  Gopi
Age  :  41
City  :  Hyderabad


Name  :  Jitendra
Age  :  52
City  :  Bangalore


Name  :  Raj
Age  :  23
City  :  Chennai

 


Previous                                                 Next                                                 Home

No comments:

Post a Comment