Pandas period to datetime conversion



0

Hi,

I have extracted day, month, year and month-year from date column in my data. I used following code.

df.as_of_date.apply(lambda x : pd.Series({
    'day': x.day, 
    'year':x.year, 
    'month': x.month, 
    'year-month': x.to_period('M')
}))

The data type of year-month column is Object. So i tried to convert it to datetime object as below:

pd.to_datetime(df['year-month'])

But i get exception:

TypeError: <class 'pandas._libs.tslibs.period.Period'> is not convertible to datetime

I am doing it so that I can use 'year-month' to plot on x-axis.

Is there another way to extract year-month information as datetime object?

Best,

KB


3 Answer(s)


0

# 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]')

 


0

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

Best, KB


0

These tips are very useful not only for beginners, but also for professionals. In turn, I want to share a service that always helps me check originality of paper and  check the percentage of text uniqueness for college.

Your Answer

Click on this code-snippet-icon icon to add code snippet.

Upload Files (Maximum image file size - 1.5 MB, other file size - 10 MB, total size - not more than 50 MB)

Email
Password