Pandas Period转to_timestamp出现TypeError

5

我有一个 Pandas 数据框,格式如下所示:

   Month     Count  
   2021-02    100
   2021-03    200  

“Month”列是从时间戳使用dt.to_period('M')获得的。

现在我必须将这个“Month”列转换为财政季度,我已经尝试使用“to_timestamp”将Period转换为“datetime”对象,但是我遇到了错误

TypeError:不支持Int64Index类型

有没有其他方法来解决这个问题?


1
你能把你的代码添加到问题中吗? - jezrael
1个回答

8

如果要使用列,则需要添加.dt。如果省略它,Pandas会尝试转换DatetimeIndex,如果不存在它,则会引发错误,因为它调用了DataFrame.to_timestamp而不是 Series.dt.to_timestamp:

df['Date'] = df['Month'].to_timestamp()

类型错误:不支持的类型 RangeIndex。

df['Date'] = df['Month'].dt.to_timestamp()
print (df)
     Month  Count       Date
0  2021-02    100 2021-02-01
1  2021-03    200 2021-03-01

财政季度的解决方案是使用 Series.dt.qyear。更好的文档在这里

df['fquarter'] = df['Month'].dt.qyear
print (df)
     Month  Count  fquarter
0  2021-02    100      2021
1  2021-03    200      2021

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接