【问题标题】:Pandas Period to to_timestamp giving me TypeError熊猫时期 to_timestamp 给我 TypeError
【发布时间】:2021-07-17 08:47:06
【问题描述】:

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

   Month     Count  
   2021-02    100
   2021-03    200  

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

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

TypeError:不支持的类型 Int64Index

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

【问题讨论】:

  • 您可以将代码添加到问题中吗?

标签: pandas datetime period


【解决方案1】:

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

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

TypeError: 不支持的类型范围索引

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。更好的文档是here:

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

【讨论】:

    猜你喜欢
    • 2018-01-01
    • 2020-07-29
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2021-01-10
    • 2019-07-19
    • 2022-10-12
    • 2016-11-09
    相关资源
    最近更新 更多