1

I have a column of dates but not all of the rows are DateTime type, some rows have string datatype, such as Jan'11, Jan 11, Jan-11. My idea is I wanna replace the split "'", and " " to be "-", then replace it to datetime format.

so this is the code that I tried,

replacers = {"'":"-"," ":"-"} 
df['Periode1'] = df['Periode1'].replace(replacers)

but when I check df[df['Periode1']=="Jan'11"] it still not change to be "Jan-11". So how to solve it?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Can you add sample data to reproduce the data frame for the test? Please [check](https://stackoverflow.com/q/20109391/8353711) for the same. – shaik moeed May 11 '22 at 17:23

1 Answers1

1

The issue is that the .replace method looks at the entire contents of each object in the series, and since there is more than just the separator in each date, the method does nothing. A better approach would be to apply a lambda function to the series:

df['Periode1'] = df['Periode1'].apply(lambda x: str(x).replace("'", "-").replace(" ", "-"))
whege
  • 1,391
  • 1
  • 5
  • 13