Pandas DataFrame.index
Pandas DataFrame.index
The DataFrame.index
property in pandas is used to access or modify the row labels (index) of a DataFrame. The index is critical for identifying rows and organizing data effectively in pandas.
Syntax
The syntax to access or modify the index of a DataFrame is:
DataFrame.index
Here, DataFrame
refers to the pandas DataFrame whose index is being accessed or modified.
Examples
Accessing the Index
You can access the index of a DataFrame using the DataFrame.index
property:
Python Program
import pandas as pd
data = {
'Name': ['Arjun', 'Ram', 'Krishna'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
# Accessing the index
print("Index:", df.index)
Output
Index: RangeIndex(start=0, stop=3, step=1)
Modifying the Index
You can assign new row labels to the DataFrame index directly:
Python Program
import pandas as pd
data = {
'Name': ['Arjun', 'Ram', 'Krishna'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
# Modifying the index
df.index = ['Row1', 'Row2', 'Row3']
# Display the updated DataFrame
print("DataFrame with Modified Index:")
print(df)
# Access the updated index
print("Updated Index:", df.index)
Output
DataFrame with Modified Index:
Name Age City
Row1 Arjun 25 New York
Row2 Ram 30 Los Angeles
Row3 Krishna 35 Chicago
Updated Index: Index(['Row1', 'Row2', 'Row3'], dtype='object')
Accessing Index Attributes
The DataFrame.index
property allows you to retrieve attributes such as the values, data type, and name of the index.
Python Program
import pandas as pd
data = {
'Name': ['Arjun', 'Ram', 'Krishna'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
# Accessing index attributes
print("Index Values:", df.index.values)
print("Index Type:", type(df.index))
Output
Index Values: [0 1 2]
Index Type:
Renaming the Index
You can assign a name to the index for better context and clarity:
Python Program
import pandas as pd
data = {
'Name': ['Arjun', 'Ram', 'Krishna'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
# Renaming the index
df.index.name = 'RowLabel'
# Display the updated DataFrame
print("DataFrame with Renamed Index:")
print(df)
# Access the index name
print("Index Name:", df.index.name)
Output
DataFrame with Renamed Index:
Name Age City
RowLabel
0 Arjun 25 New York
1 Ram 30 Los Angeles
2 Krishna 35 Chicago
Index Name: RowLabel
Summary
In this tutorial, we explored the DataFrame.index
property in pandas. We learned how to access the index, modify it, retrieve its attributes, and rename it. The index is an essential part of pandas DataFrames, enabling efficient row identification and data manipulation.