How to Get Index of Pandas DataFrame?


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.

Syntax

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.

Examples

1. Get index of given DataFrame df

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)

Output

RangeIndex(start=0, stop=3, step=1)

2. Iterate over index and print

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)

Output

0
1
2

3. Get index of DataFrame that has been initialised with specific index

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)

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.