Reputation: 93
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...
Upvotes: 0
Views: 2054
Reputation: 2513
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']
Upvotes: 0
Reputation: 78750
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
Upvotes: 3
Reputation: 18426
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)
Upvotes: 2