.index
Published May 12, 2024
Contribute to Docs
The .index
attribute represents the row labels (index) of the DataFrame. It returns an Index
object and can be used to view or assign new values to the row labels.
Syntax
pandas.DataFrame.index
Example
In the following example, the .index
attribute is used to view and modify the row labels of the monthlyCost
DataFrame:
import pandas as pd# Creating the DataFrame representing monthly cost of 4 itemsdata = {'April': [88, 92, 79, 85],'May': [94, 77, 90, 78],'June': [89, 80, 95, 81]}monthlyCost = pd.DataFrame(data)# Print the DataFrameprint(f'{monthlyCost} \n')# modify the row labelsmonthlyCost.index = ['bread', 'milk', 'apples', 'onions']# print the modified monthlyCost Dataframeprint(f'{monthlyCost} \n')# print the row label or index of monthlyCost DataFrameprint(monthlyCost.index)
The output for the above code is as follows:
April May June0 88 94 891 92 77 802 79 90 953 85 78 81April May Junebread 88 94 89milk 92 77 80apples 79 90 95onions 85 78 81Index(['bread', 'milk', 'apples', 'onions'], dtype='object')
Codebyte Example
The following Codebyte Example demonstrates how to view and update a DataFrame using the .index
attribute:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.