使用 .to_timestamp() 转换句点对象会产生类型错误

Conversion of period object with .to_timestamp() generates type error

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

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

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

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 to timestamp

结果类型错误:

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

有人知道为什么句点对象不能与 .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()

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

尝试使用 .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')