我有一个 Pandas 数据框,格式如下所示:
Month Count
2021-02 100
2021-03 200
“Month”列是从时间戳使用dt.to_period('M')获得的。
现在我必须将这个“Month”列转换为财政季度,我已经尝试使用“to_timestamp”将Period转换为“datetime”对象,但是我遇到了错误
TypeError:不支持Int64Index类型
有没有其他方法来解决这个问题?
我有一个 Pandas 数据框,格式如下所示:
Month Count
2021-02 100
2021-03 200
“Month”列是从时间戳使用dt.to_period('M')获得的。
现在我必须将这个“Month”列转换为财政季度,我已经尝试使用“to_timestamp”将Period转换为“datetime”对象,但是我遇到了错误
TypeError:不支持Int64Index类型
有没有其他方法来解决这个问题?
如果要使用列,则需要添加.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