Examples of how to rename a column name of a DataFrame in pandas:
Rename a column name using rename()
Let's consider the following dataframe
>>> 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
To rename for example the column called 'c1' a solution is to use the pandas function 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
Note: the edit here is not saved:
>>> 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
To save the edit, it is necessary to add inplace=True:
>>> 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
Rename multiple column names
It is also possible to rename multiple column names:
>>> 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
Add a prefix to column names
To add a prefix to all the column names a solution is to use add_prefix(), example
>>> 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
Add a suffix to column names
To add a suffix to all the column names a solution is to use add_suffix, example:
>>> 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
References
| Lnks | Site |
|---|---|
| rename() | pandas doc |
| pandas: Rename index / columns names (labels) of DataFrame | note.nkmk.me |
| add_prefix() | pandas doc |
| add_suffix | pandas doc |
