Exemple de comment utiliser une colonne d'une dataframe comme indice avec pandas en python
Créer une dataframe
Créons un dataframe avec des 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)
donne
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
Définir une colonne comme indice d'une dataframe
Pour par exemple utiliser la colonne nommée Id comme indice de la dataframe, une solution est d'utiliser pandas.DataFrame.set_index:
df.set_index('Id', inplace=True)print(df)
donne ici
Age weight Gender CountryIdjch2c1 21 120 male France63jc2h 26 148 male USAhg217d 82 139 female USAhj127b 15 156 male Germanyedew32 28 129 female USA
Réinitialiser les indices d'une dataframe
Pour réinitialiser les indices d'une dataframe, une solution est d'utiliser reset_index(), (voir How to reset dataframe index with pandas in python ?)
df.reset_index(drop=False, inplace=True)print(df)
donne
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
