Pandas period to datetime conversion


2 Answer(s)


# Random Data
df = pd.DataFrame({
    'as_of_date': pd.to_datetime(np.random.randint(3*10**9, 5*10**9, 20),
                                 unit='s')
})

# The manipulation you did
df2 = df.as_of_date.apply(lambda x : pd.Series({
    'day': x.day, 
    'year':x.year, 
    'month': x.month, 
    'year-month': x.to_period('M')
}))

# What you need
df2['ym'] = df.as_of_date.values.astype('datetime64[M]')

 


Pretty neat trick GPS, It worked! Thanks a lot!!

Best, KB