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'])
>>> df
c1 c2 c3 c4 c5
0 33 93 44 10 38
1 77 27 78 15 84
2 33 50 42 30 63
3 35 54 39 8 21
4 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 c5
0 33 93 44 10 38
1 77 27 78 15 84
2 33 50 42 30 63
3 35 54 39 8 21
4 77 11 3 89 41
Note: the edit here is not saved:
>>> df
c1 c2 c3 c4 c5
0 33 93 44 10 38
1 77 27 78 15 84
2 33 50 42 30 63
3 35 54 39 8 21
4 77 11 3 89 41
To save the edit, it is necessary to add inplace=True:
>>> df.rename(columns={'c1': 'Price'}, inplace=True)
>>> df
Price c2 c3 c4 c5
0 33 93 44 10 38
1 77 27 78 15 84
2 33 50 42 30 63
3 35 54 39 8 21
4 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)
>>> df
Price Product Tag c4 c5
0 33 93 44 10 38
1 77 27 78 15 84
2 33 50 42 30 63
3 35 54 39 8 21
4 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_c5
0 33 93 44 10 38
1 77 27 78 15 84
2 33 50 42 30 63
3 35 54 39 8 21
4 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_vol
0 33 93 44 10 38
1 77 27 78 15 84
2 33 50 42 30 63
3 35 54 39 8 21
4 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 |