1

I am trying to rename the last column in this df:

    Entity  Year    Sales of cigarettes per adult per day (International Smoking Statistics(2017))
0   Armenia 1988    12.0
1   Armenia 1989    11.6
2   Armenia 1990    11.9
3   Armenia 1991    9.3
4   Armenia 1992    4.9

However, no code that I try will work, the column name just stays the same. So far I have run:

df_cig_sales.rename({'''Sales of cigarettes per adult per day (International Smoking Statistics (2017))''':'Cigs per adult per day'},
 axis=1, inplace=True)

df_cig_sales.rename({'Sales of cigarettes per adult per day (International Smoking Statistics (2017))':'Cigs per adult per day'},
 axis=1, inplace=True)

df_cig_sales.rename(columns={'Sales of cigarettes per adult per day (International Smoking Statistics (2017))':'Cigs per adult per day'},
 inplace=True)

Putting the column names to a list gives me:

print(df_cig_sales.columns.tolist())

>>>>['Entity', 'Year', 'Sales of cigarettes per adult per day (International Smoking Statistics (2017)) ']

Is there something that I am missing? This code is running without any errors. Any help would be awesome. Thank you.

Ven
  • 37
  • 1
  • 9

1 Answers1

1

This should works if you remove the trailing whitespace:

s = 'Sales of cigarettes per adult per day (International Smoking Statistics(2017)) '
df_cig_sales.rename(columns={s: 'Cigs per adult per day'}, inplace=True)
>>> s
'Sales of cigarettes per adult per day (International Smoking Statistics (2017)) '
#                                                   Trailing whitespace here ---^
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • It didn't work. I tried it both by setting the column name to a variable without a white space as you demonstrated and also just deleting that space in the dictionary from all of my previous examples. – Ven May 12 '22 at 01:23
  • Update your post with the output of `print(df_cig_sales.columns.tolist())` please – Corralien May 12 '22 at 01:25
  • Done... it's the dumb space at the end of the column name... isn't it. – Ven May 12 '22 at 01:27
  • No... that didn't do it. – Ven May 12 '22 at 01:28
  • It wound up working, but only when I took the ''' down to '. – Ven May 12 '22 at 01:29