Pandas 周期到 to_timestamp 给我 TypeError

sag*_*c_k 5 datetime period pandas

我有一个格式如下所示的 Pandas Dataframe:

   Month     Count  
   2021-02    100
   2021-03    200  
Run Code Online (Sandbox Code Playgroud)

其中“月”列是使用dt.to_period('M')从时间戳获取的。

现在我必须将此“月份”列转换为会计季度,并且我使用了一些方法使用“to_timestamp”将期间转换为“日期时间”对象,但出现错误

类型错误:不支持的 Int64Index 类型

还有其他方法可以解决这个问题吗?

jez*_*ael 8

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

df['Date'] = df['Month'].to_timestamp()
Run Code Online (Sandbox Code Playgroud)

类型错误:不支持的类型 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
Run Code Online (Sandbox Code Playgroud)

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

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