0

I am trying to loop through the titles of a dataframe and change them to the last character of the title so then I can convert them to months. I want a loop because I get data each month and I want to have it automated so I don't manually add the title names. When I print the titles this is what I get:

list(df)

['MCA036_LIFETIME_1', 'MCA036_LIFETIME_2', 'MCA036_LIFETIME_3', 'Total']

I would like for the titles to be:

list(df)

['January','February','March','Total']

Any guidance would be greatly appreciated.

1 Answers1

3

You don't need loop, just:

df.columns = ['January','February','March','Total']

If you want to automatically convert the string in that list, it's a general Python problem, not particularly related to pandas:

In [141]: all_monthes = ['January', 'February', 'March']

In [142]: l = ['MCA036_LIFETIME_1', 'MCA036_LIFETIME_2', 'MCA036_LIFETIME_3', 'Total']

In [143]: [all_monthes[int(e.split('_')[-1])-1] if e != 'Total' else e for e in l]
Out[143]: ['January', 'February', 'March', 'Total']
llllllllll
  • 16,169
  • 4
  • 31
  • 54