Get Index of DataFrame

To get index of DataFrame in Pandas, use DataFrame.index attribute. DataFrame.index allows us to access the index of this DataFrame.

In this tutorial, we will learn how to get index of DataFrame in Pandas using DataFrame.index attribute.

Examples

Default Index of DataFrame

In the following program, we take a DataFrame with default index, and read the index of this DataFrame using DataFrame.index property.

Example.py

</>
Copy
import pandas as pd

df = pd.DataFrame(
    {'name': ["apple", "banana", "cherry"], 'quant': [40, 50, 60]})

print(df.index)

Output

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

We may convert the index to a list using list() builtin function.

Example.py

</>
Copy
import pandas as pd

df = pd.DataFrame(
    {'name': ["apple", "banana", "cherry"], 'quant': [40, 50, 60]})

print(list(df.index))

Output

[0, 1, 2]

Index of DataFrame

In the following program, we take a DataFrame with specific index provided during initialization. We shall then read this Index of DataFrame and print it to console.

Example.py

</>
Copy
import pandas as pd

df = pd.DataFrame([["apple", 40], ["banana", 50], ["cherry", 60]],
                  columns=['name', 'quant'],
                  index=[142, 332, 521])

print(df.index)

Output

Int64Index([142, 332, 521], dtype='int64')

Conclusion

In this Pandas Tutorial, we learned how to get the index of a DataFrame using DataFrame.index attribute.