首页 > 解决方案 > 使用 .to_timestamp() 转换周期对象会产生类型错误

问题描述

我有一个包含日期(日期时间对象)的数据框,我只想在新列 df['month_year'] 中更改为月份和年份(例如 2021-04)。意图是在 plotly express 中使用折线图的 x 轴中的月份年份值。

df['month_year'] = pd.to_datetime(df['Case Created Date']).dt.to_period('M')

结果是一个 period 对象,看起来不错:

28934    2021-04
23078    2020-09
23079    2020-09
23081    2020-09
23082    2020-09
Name: month_year, dtype: period[M]

但是'month_year'值还不能用作x轴,我发现并在这里描述了错误: modifying-extending-jsonencoder-for-panda-dataframe-timespan-objects

所以我把它扩展了

df['month_year'].to_timestamp(freq='M')

根据Period 到时间戳

结果是类型错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-147-fb01a99cffce> in <module>
      2 print(df['month_year'].head())
      3 
----> 4 df['month_year'].to_timestamp(freq='M')
      5 
      6 #df['month_year_2'].head()

~\Anaconda3\lib\site-packages\pandas\core\series.py in to_timestamp(self, freq, how, copy)
   4921 
   4922         if not isinstance(self.index, PeriodIndex):
-> 4923             raise TypeError(f"unsupported Type {type(self.index).__name__}")
   4924         new_index = self.index.to_timestamp(freq=freq, how=how)  # type: ignore
   4925         return self._constructor(new_values, index=new_index).__finalize__(

TypeError: unsupported Type Int64Index

有人知道为什么 period 对象不能与 .to_timestamp() 一起使用吗?谢谢!

更新以下评论:我创建了一个以 df 作为参数的函数。然后该函数开始于:

    #Grouping
    group = df.groupby(['month_year', 'Case Sub Area'], as_index = False)['All Cases'].count()
    group = group.sort_values(by='month_year')
    group = group['month_year'].dt.to_timestamp()

我知道最后一行是垃圾,但我无法按预期运行(请参阅下面对您的回复的评论)。

标签: pythondatetimetimestampplotly

解决方案


尝试使用 .dt,因为您正在处理一个系列。

所以而不是:

df['month_year'].to_timestamp(freq='M')

采用:

df['month_year'].dt.to_timestamp(freq='M')

就地更改整个列:

df['month_year'] = df['month_year'].dt.to_timestamp(freq='M')

推荐阅读