Using a map to rename columns

Screen Link:

My Code:

merged['IncomeGroup'] = merged['IncomeGroup'].str.lower()
mapping = {'upper middle income': 'UPPER MIDDLE', 'lower middle income': 'LOWER MIDDLE', 'high income: oecd': 'HIGH OECD','low income' : 'LOW','high income nonoecd' : 'HIGH NONOECD'}

merged = merged.rename(mapping,axis=1)

pv_incomes = merged.pivot_table(values='Happiness Score', index='IncomeGroup')
pv_incomes.plot(kind='bar', rot=30, ylim=(0,10))
plt.show()

What I expected to happen:
Columns would be renamed according to the mapping dictionary. This technique was used previously and again later in guided project 348 (screen 3).

What actually happened:

columns aren't renamed

Why are the columns not being renamed? I also tried using a for loop as below

# for k in  merged['IncomeGroup']:
#     k.replace('upper middle income','UPPER MIDDLE')
#     k.replace('lower middle income','LOWER MIDDLE')
#     k.replace('high income: oecd','HIGH OECD')
#     k.replace('low income','LOW')
#     k.replace('high income nonoecd','HIGH NONOECD')

but this didn’t work either. Basically the solution provided is very inelegant and I think a mapping dictionary works much better, but I can’t figure out where I’m going wrong. I’ve tried limiting it to a column, or removing the axis, or doing inplace = 1 but not able to get it working. Thanks for any input!

merged = merged.rename(mapping,axis=1)

This code will rename the column label according to the mapping dictionary, but it will not rename the column value. The lesson is asking you to change the column values, not their labels. You need to use a combination of the listed functions Series.str.replace(), Series.str.lower(), etc. in order to change the column values.

You can use for loops to replace the values, but this would be worse performing than using the vectorized functions listed.

1 Like

That makes sense, thank you!