How to use a dataframe column as index with pandas ?

August 11, 2021    /    Viewed: 306    /    Comments: 0    /    Edit


Example of how to set a Column as Index in Pandas DataFrame:

Create a dataframe

Lets create a dataframe with pandas

import pandas as pd

data = {'Age':[21,26,82,15,28],
                'Id':['jch2c1','63jc2h','hg217d','hj127b','edew32'],
                'weight':[120,148,139,156,129],
             'Gender':['male','male','female','male','female'],
             'Country':['France','USA','USA','Germany','USA']}

df = pd.DataFrame(data=data)

print(df)

returns

     Age      Id  weight  Gender  Country
0   21  jch2c1     120    male   France
1   26  63jc2h     148    male      USA
2   82  hg217d     139  female      USA
3   15  hj127b     156    male  Germany
4   28  edew32     129  female      USA

Set a column as Index in Pandas DataFrame

We want for example here to set the column named Id as index of the dataframe. To do that a solution is to use pandas.DataFrame.set_index

df.set_index('Id', inplace=True)

print(df)

returns

                Age  weight  Gender  Country
Id                                  
jch2c1   21     120    male   France
63jc2h   26     148    male      USA
hg217d   82     139  female      USA
hj127b   15     156    male  Germany
edew32   28     129  female      USA

Reset dataframe index

To reset dataframe index, a solution is to do (see also How to reset dataframe index with pandas in python ?)

df.reset_index(drop=False, inplace=True)

print(df)

returns

       Id  Age  weight  Gender  Country
0  jch2c1   21     120    male   France
1  63jc2h   26     148    male      USA
2  hg217d   82     139  female      USA
3  hj127b   15     156    male  Germany
4  edew32   28     129  female      USA

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!