EDIT:
This is similar to stackoverflow.com/questions/36531675/rename-columns-in-pandas-based-on-dictionary but it is not the same.
Given that I already have defined a dictionary how do I map the column names? Besed on the above answer I try this but it gives me NaN
values.
test = df.columns.to_series().map(columns)
----- End edit -----
I have a pandas dataframe something like this:
df = pd.DataFrame(
{'id': [1, 2, 3, 4, 5],
'oldname1': ['something'] *5,
'old_name1': [1.10, 1.12, 1.23, 1.03, 1.22],
'oldname_1': [1.10, 1.12, 1.23, 1.03, 1.22],
'oldname1': ['ABC123'] * 5
})
I want to rename the columns using df.columns = ['list of new columns']
The columns to be changed are stored in a dict:
columns = {
'oldname1': 'new_nameA',
'old_name1': 'new_nameB',
'oldname_1': 'new_nameC',
'oldname_2': 'new_nameD'
}
To rename I do the following:
new_column_names = []
for col in df:
col = col.lower()
if col in columns.keys():
for key in columns.keys():
new_col = col.lower().replace(key, columns[key])
if new_col not in new_column_names:
new_column_names.append(new_col)
else:
new_column_names.append(col)
At this point the new_column_names
are: ['id', 'new_name1', 'oldname1', 'old_name1', 'oldname_1']
Once correct I can update the dataframe's columns
df.columns = new_column_names
Where am I going wrong? Can I code this better?