Warm tip: This article is reproduced from serverfault.com, please click

Using PeriodIndex to convert dates

发布于 2019-04-15 16:49:15

I am trying to use PeriodIndex to create quarters, days, years but recently the function stopped working for some reason. Below is a min examples:

 dict = [{'Date': '12/23/18'},
 {'Date': '12/24/18'},
 {'Date': '12/22/18'},
 {'Date': '12/24/18'},
 {'Date': '12/22/18'},
 {'Date': '12/24/18'}]
 df = pd.DataFrame(dict)
 df['Date2']      = pd.to_datetime(df['Date']).dt.date 
 df['year']        =    pd.PeriodIndex(df['Date2'], freq='A') 

I get this error:

 TypeError: Incorrect dtype

This used to work before but I am not sure why it does not work anymore.

Edt: I just noticed that the above commands work perfectly fine on my other computer (same version of Python, Win 10).

Questioner
Tartaglia
Viewed
0
Rens 2020-01-22 17:03:56

You can add .values to your date. So df['year'] = pd.PeriodIndex(df['Date2'].values, freq='A') This will work!

I run into the same problem after reinstaling and upgrading Pandas. Newer versions of Pandas accept date strings that are read as a np.array using .values (as the author of this GitHub post also found).