Set Index for DataFrame

To set index for DataFrame in Pandas, we may specify the index during initialization of DataFrame via index parameter, or set the index after initialization of DataFrame using DataFrame.index attribute.

In this tutorial, we will learn how to set index for DataFrame in Pandas using DataFrame() constructor and DataFrame.index attribute.

Examples

Specify Index in DataFrame Constructor

In the following program, we create a DataFrame with specific index using index parameter. We pass a list of integers for the index. The length of this index must be equal to the number of rows initialized.

Example.py

</>
Copy
import pandas as pd

df = pd.DataFrame([["apple", 40], ["banana", 50], ["cherry", 60]],
                  columns=['name', 'quant'],
                  index=[112, 113, 114])

print(df)

Output

       name  quant
112   apple     40
113  banana     50
114  cherry     60

Set Index for DataFrame via DataFrame.index attribute

In the following program, we take a DataFrame and set its index using DataFrame.index attribute. We pass an integer list for the index.

Example.py

</>
Copy
import pandas as pd

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

df.index=[112, 113, 114]

print(df)

Output

       name  quant
112   apple     40
113  banana     50
114  cherry     60

Conclusion

In this Pandas Tutorial, we learned how to set the index of a DataFrame using DataFrame() constructor or DataFrame.index attribute.