Pandas DataFrame.axes
Pandas DataFrame.axes
The DataFrame.axes property in pandas is used to return a list of row and column axis labels for the DataFrame. This is a convenient way to inspect the structure of the DataFrame by accessing the index (rows) and columns.
Syntax
The syntax for accessing the axes property is:
DataFrame.axesHere, DataFrame refers to the pandas DataFrame whose axes (row and column labels) are being accessed.
Returns
A list containing two elements:
Index: Row axis labels (index).Index: Column axis labels (columns).
Examples
Accessing Axes Labels
You can use the axes property to access the row and column labels of a DataFrame.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Suresh'],
'Age': [25, 30, 35],
'Salary': [70000, 80000, 90000]
}
df = pd.DataFrame(data)
# Access the axes of the DataFrame
print("Row and Column Axes:")
print(df.axes)Output
Row and Column Axes:
[RangeIndex(start=0, stop=3, step=1), Index(['Name', 'Age', 'Salary'], dtype='object')]Accessing Row Axis (Index)
You can access only the row axis labels (index) by selecting the first element of the axes list.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Suresh'],
'Age': [25, 30, 35],
'Salary': [70000, 80000, 90000]
}
df = pd.DataFrame(data)
# Access the row axis labels
print("Row Axis (Index):")
print(df.axes[0])Output
Row Axis (Index):
RangeIndex(start=0, stop=3, step=1)Accessing Column Axis (Columns)
You can access only the column axis labels by selecting the second element of the axes list.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Suresh'],
'Age': [25, 30, 35],
'Salary': [70000, 80000, 90000]
}
df = pd.DataFrame(data)
# Access the column axis labels
print("Column Axis (Columns):")
print(df.axes[1])Output
Column Axis (Columns):
Index(['Name', 'Age', 'Salary'], dtype='object')Using Axes in Operations
You can use the axes property in operations, such as renaming or iterating over row and column labels.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Suresh'],
'Age': [25, 30, 35],
'Salary': [70000, 80000, 90000]
}
df = pd.DataFrame(data)
# Rename columns using the column axis labels
new_columns = [col.upper() for col in df.axes[1]]
df.columns = new_columns
print("DataFrame with Renamed Columns:")
print(df)Output
DataFrame with Renamed Columns:
NAME AGE SALARY
0 Arjun 25 70000
1 Ram 30 80000
2 Suresh 35 90000Summary
In this tutorial, we explored the DataFrame.axes property in pandas. Key points include:
- Using
axesto access row and column labels - Accessing the row axis (index) and column axis separately
- Using axes in operations like renaming columns
The DataFrame.axes property is a simple yet powerful tool for inspecting the structure of a DataFrame and performing label-based operations.