collarblind
collarblind

Reputation: 4739

Pandas column date transformation

I have a pandas dataframe with a date column the data type is datetime64[ns]. there are over 1000 observations in the dataframe. I want to transform the following column:

date
2013-05-01
2013-05-01

to

date
05/2013
05/2013

or

date
05-2013
05-2013

EDIT//

this is my sample code as of now

test = pd.DataFrame({'a':['07/2017','07/2017',pd.NaT]})

           a
0 2017-07-13
1 2017-07-13
2        NaT

test['a'].apply(lambda x: x if pd.isnull(x) == True else x.strftime('%Y-%m'))

0   2017-07-01
1   2017-07-01
2          NaT
Name: a, dtype: datetime64[ns]

why did only the date change and not the format?

Upvotes: 1

Views: 345

Answers (1)

maxymoo
maxymoo

Reputation: 36545

You can convert datetime64 into whatever string format you like using the strftime method. In your case you would apply it like this:

df.date = df.date[df.date.notnull()].map(lambda x: x.strftime('%m/%Y'))
df.date
Out[111]: 
0    05/2013
1    05/2013

Upvotes: 2

Related Questions