Exemples de comment renommer une ou des colonnes d'un tableau de données (DataFrame) avec pandas sous python:
Renommer une colonne avec rename()
Soit la DataFrame suivante:
>>> import numpy as np>>> import pandas as pd>>> import numpy as np>>> data = np.random.randint(100, size=(5,5))>>> df = pd.DataFrame(data=data,columns=['c1','c2','c3','c4','c5'])>>> dfc1 c2 c3 c4 c50 33 93 44 10 381 77 27 78 15 842 33 50 42 30 633 35 54 39 8 214 77 11 3 89 41
Pour renommer par exemple la colonne c1 on peut utiliser la fonction pandas rename():
>>> df.rename(columns={'c1': 'Price'})Price c2 c3 c4 c50 33 93 44 10 381 77 27 78 15 842 33 50 42 30 633 35 54 39 8 214 77 11 3 89 41
Attention ici la modification de la DataFrame n'est pas conservée
>>> dfc1 c2 c3 c4 c50 33 93 44 10 381 77 27 78 15 842 33 50 42 30 633 35 54 39 8 214 77 11 3 89 41
Pour conserver la modification il faut ajouter inplace=True comme ceci:
>>> df.rename(columns={'c1': 'Price'}, inplace=True)>>> dfPrice c2 c3 c4 c50 33 93 44 10 381 77 27 78 15 842 33 50 42 30 633 35 54 39 8 214 77 11 3 89 41
Renommer plusieurs colonnes
On peut aussi renommer plusieurs colonnes en même temps:
>>> df.rename(columns={'c2': 'Product', 'c3':'Tag'}, inplace=True)>>> dfPrice Product Tag c4 c50 33 93 44 10 381 77 27 78 15 842 33 50 42 30 633 35 54 39 8 214 77 11 3 89 41
Ajouter un préfixe aux titres des colonnes
On peut aussi ajouter un préfixe avec la fonction add_prefix()
>>> df.add_prefix('data_')data_price data_product data_tag data_c4 data_c50 33 93 44 10 381 77 27 78 15 842 33 50 42 30 633 35 54 39 8 214 77 11 3 89 41
Ajouter un suffixe aux titres des colonnes
On peut aussi ajouter un suffixe avec la fonction add_suffix
>>> df.add_suffix('_vol')price_vol product_vol tag_vol c4_vol c5_vol0 33 93 44 10 381 77 27 78 15 842 33 50 42 30 633 35 54 39 8 214 77 11 3 89 41
Références
| Liens | Site |
|---|---|
| rename() | pandas doc |
| pandas: Rename index / columns names (labels) of DataFrame | note.nkmk.me |
| add_prefix() | pandas doc |
| add_suffix | pandas doc |
