Comment utiliser une colonne d'une dataframe comme indice avec pandas en python ?

Published: 19 août 2021

Tags: Python; Pandas; DataFrame; Index; Column;

DMCA.com Protection Status

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 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)

donne

     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

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  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

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  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

Références