0

So I have a dataframe where a row called 'Months' has entries in form: 1M , 12M etc. So I wanted to get rid of the M letter. I have tried using the .replace() function but had no success in doing so: df['Months'].replace('M','') what is wrong in my implementation and how can I correct it?

Thanks

Huzo
  • 1,652
  • 1
  • 21
  • 52

2 Answers2

3

I think you're looking for ".str.replace", i.e.:

df['Months'] = df['Months'].str.replace('M','')

The ".str" functions apply a string function to each entry of the database; instead the ".replace" one replaces all objects, so in case you should be doing:

for i in range(1,13):
    df['Months'] = df['Months'].replace('{}M'.format(i),str(i))

which is of course clumsier and likely slower.

Marco Spinaci
  • 1,750
  • 15
  • 22
2

Use df['Months'].str.replace('M', '').

The difference:

jpp
  • 159,742
  • 34
  • 281
  • 339