python - 使用 .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')
结果是类型错误:
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()
我知道最后一行是垃圾,但我无法按预期运行(请参阅下面对您的回复的评论)。
解决方案
尝试使用 .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')
推荐阅读
- html - 坚持第一和最后 | html表格中的左右列
- c++ - 为什么 getline 只读取第一个笔画?
- android - ExoPlayer2 - 在 playerView.setRotation(90) 之后调整视频大小
- php - Laravel如何根据选中的复选框存储值
- javascript - Is it possible to use both CommonJS and ES6 module in a Node.JS command-line program?
- python - 为什么我不能调用这个函数?Discord.py 和 ASYNC/AWAIT 问题
- html - 为什么是 justify-content: flex-start; 不工作?
- c# - 比较数组的所有元素的最快等价物
- batch-file - 如何运行 PowerShell 命令以删除批处理脚本中持久存储的用户环境变量?
- c++ - 为什么基于for循环的范围内的二维数组的元素是T*而不是T(*)[n]?