0

I have a column in which there are dates :

df['Date']

    Date
0 2020-25-04
1 2020-26-04
2 2020-27-04
3 2020-12-05
4 2020-06-05
Name: Date, Length: 5, dtype: datetime64[ns]

I want to swap the element Day by element Month, so I can have :

df['Date']

     Date
0 2020-04-25
1 2020-04-26
2 2020-04-27
3 2020-05-12
4 2020-05-06
Name: Date, Length: 5, dtype: datetime64[ns]

Any help would be appreciated.

user51
  • 8,843
  • 21
  • 79
  • 158
K. ossama
  • 403
  • 1
  • 4
  • 15
  • Do you want to the output to be a string or do you want pandas in general to display dates in your custom format? – cmosig May 15 '20 at 14:02
  • I want to display it in the datetime format, just as it is. – K. ossama May 15 '20 at 14:07
  • how did you end up with a datetime series like your input? as I can see the dtype is not object but datetime – anky May 15 '20 at 14:08
  • it was like this : 25/04/2020 with type 'object'. and then, I converted it to datetime using this code : df['Date']=pd.to_datetime(df['Date']) – K. ossama May 15 '20 at 14:12
  • can you try converting `pd.to_datetime(df['Date'],dayfirst=True)` as a first step? – anky May 15 '20 at 16:02

1 Answers1

0
import pandas as pd
import numpy as np

df = pd.DataFrame({'Date':[np.datetime64('2020-04-25') ,np.datetime64('2020-04-26')]})

df['Date'] = df['Date'].apply(lambda x: x.strftime('%Y-%m-%d'))

print(df)

I converted data into np.datetime format and applied lambda function.

SahilDesai
  • 512
  • 3
  • 6