Pandas DataFrame – Get Index
To get the index of a Pandas DataFrame, call DataFrame.index property. The DataFrame.index property returns an Index object representing the index of this DataFrame.
The syntax to use index property of a DataFrame is
DataFrame.index
The index property returns an object of type Index. We could access individual index using any looping technique in Python.
In the following program, we have a DataFrame with no index specified. Since no index is specified, a range that starts at 0 and increments in steps of 1 would be assigned to the DataFrame. Let us get the index of this DataFrame using DataFrame.index.
Python Program
import pandas as pd
df = pd.DataFrame(
[[88, 72, 67],
[23, 78, 62],
[55, 54, 76]],
columns=['a', 'b', 'c'])
index = df.index
print(index)
Run Output
RangeIndex(start=0, stop=3, step=1)
We can print the elements of Index object using a for loop as shown in the following.
Python Program
import pandas as pd
df = pd.DataFrame(
[[88, 72, 67],
[23, 78, 62],
[55, 54, 76]],
columns=['a', 'b', 'c'])
index = df.index
for i in index:
print(i)
Run Output
0
1
2
Let us consider another example, where we have set a specific index for a DataFrame. And we are going to get the index of this DataFrame using DataFrame.index.
Python Program
import pandas as pd
df = pd.DataFrame(
[[88, 72, 67],
[23, 78, 62],
[55, 54, 76]],
index=[2, 4, 9],
columns=['a', 'b', 'c'])
index = df.index
print(index)
Run Output
Int64Index([2, 4, 9], dtype='int64')
Summary
In this tutorial of Python Examples, we learned how to get the index of a DataFrame using DataFrame.index property.