python - 如何在 groupby dayofweek 之后获取 day_name()?
问题描述
我有一个DatetimeIndex
索引系列 s1
s1
time
2021-08-24 09:24:16+09:00 11933142
2021-08-24 10:00:03+09:00 11785209
2021-08-24 11:00:03+09:00 14462866
2021-08-24 19:00:04+09:00 11419204
2021-08-24 20:00:03+09:00 11757634
Name: x, dtype: int64
并且想要mean()
一周中的每一天。然后我想获取day_name()
索引来绘制图形标签,但我不能,因为DatetimeIndex
现在变成了 int。
g1 = s1.groupby(s1.index.dayofweek).mean()
----> 3 g1.index.day_name()
AttributeError: 'Int64Index' object has no attribute 'day_name'
最聪明的解决方法是什么?
解决方案
分组方式day_name
:
>>> s1.groupby(s1.index.day_name()).mean()
Tuesday 12271611.0
Name: time, dtype: float64
图表示例:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import calendar
days = list(calendar.day_name)
s2 = pd.Series(np.random.randint(1000, 10000, 365),
index=pd.date_range('2021-01-01', '2021-12-31'))
s2.groupby(s2.index.day_name()).mean().reindex(days).plot(kind='bar', rot=45)
plt.show()
推荐阅读
- python - 限制 SQLite3 SELECT 查询中选择的唯一日期的数量
- java - 如何从服务器关闭之前的最后一个状态恢复弹簧状态机?
- ios - 通用 AlertViewController 适用于所有视图控制器
- html - 如何在反应中显示半透明的div?
- python - 如何按新评论对评论进行排序,并阻止我的机器人评论相同的评论?
- java - PipedOutput/InputStream 使用 spring 集成上传到 sftp
- sceneform - 如何在 Android 上将 .hdr 文件读取到图像数组?
- csv - Snowflake COPY INTO 从舞台丢失行
- svg - 将 SVG 线从直线变形为展开
- android - Android - 使用 espresso 启动片段传递导航参数