'How to replace pandas dataframe column names with another list or dictionary matching

I need to replace column names of a pandas DataFrame having names like 'real_tag' and rename them like 'Descripcion'

list = [{'real_tag': 'FA0:4AIS0007', 'Descripcion': 'velocidad burbujas celda 7'}, {'real_tag': 'FA0:4FIC0116_PVLOLM', 'Descripcion': 'LIMITE BAJO FLUJO AIRE CELDA 2 FLOT. A0'}]

Is there any way I can achieve this? Names need to match...



Solution 1:[1]

Create a dictionary mapping old to new names, then use DataFrame.rename.

Setup

>>> lst = [{'real_tag': 'FA0:4AIS0007', 'Descripcion': 'velocidad burbujas celda 7'}, {'real_tag': 'FA0:4FIC0116_PVLOLM', 'Descripcion': 'LIMITE BAJO FLUJO AIRE CELDA 2 FLOT. A0'}]                                                   
>>> df = pd.DataFrame([[1, 2, 3]], columns=['FA0:4AIS0007', 'FA0:4FIC0116_PVLOLM', 'X'])                                                                                                                                               
>>> df                                                                                                                                                                                                                                 
   FA0:4AIS0007  FA0:4FIC0116_PVLOLM  X
0             1                    2  3

Solution

>>> mapping = {d['real_tag']:d['Descripcion'] for d in lst} 
>>> df.rename(mapping, axis='columns')                                                                                                                                                                                                 
   velocidad burbujas celda 7  LIMITE BAJO FLUJO AIRE CELDA 2 FLOT. A0  X
0                           1                                        2  3

Solution 2:[2]

You can use rename method of dataframe and pass dictionary (key as old name, value as new name) to the columns argument.

given a dataframe df and your list of columns list:

df.rename(columns={item['real_tag']:item['Descripcion'] for item in list}, inplace=True)

Solution 3:[3]

Once you set a data frame, you can edit its columns attribute to change the names. Be careful though, you need to keep the column order constant:

df = pd.DataFrame([[1, 3, 5], [2, 4, 6]],    columns=['alpha', 'beta', 'gamma'])
df.columns = ['Alpha', 'Beta', 'Gamma']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 timgeb
Solution 2 ThePyGuy
Solution 3