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

python-使用PeriodIndex转换日期

(python - Using PeriodIndex to convert dates)

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

我正在尝试使用PeriodIndex创建季度,天,年,但是最近该函数由于某种原因停止工作。下面是一个最小的示例:

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

我收到此错误:

 TypeError: Incorrect dtype

这以前曾经起作用,但我不确定为什么它不再起作用了。

Edt:我刚刚注意到上面的命令在我的另一台计算机上工作得很好(相同版本的Python,Win 10)。

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

你可以添加.values到你的日期。因此,df['year'] = pd.PeriodIndex(df['Date2'].values, freq='A')这将起作用!

在重新安装和升级Pandas之后,我遇到了同样的问题。大 pandas 的较新版本接受读为使用np.array日期字符串.values(如笔者这样的GitHub后也发现)。