Example of how to set a Column as Index in Pandas DataFrame:
Create a dataframe
Lets create a dataframe with pandas
import pandas as pddata = {'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 Country0 21 jch2c1 120 male France1 26 63jc2h 148 male USA2 82 hg217d 139 female USA3 15 hj127b 156 male Germany4 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 CountryIdjch2c1 21 120 male France63jc2h 26 148 male USAhg217d 82 139 female USAhj127b 15 156 male Germanyedew32 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 Country0 jch2c1 21 120 male France1 63jc2h 26 148 male USA2 hg217d 82 139 female USA3 hj127b 15 156 male Germany4 edew32 28 129 female USA
