首页 > 解决方案 > 如何在 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'


最聪明的解决方法是什么?

标签: pythonpandasdayofweek

解决方案


分组方式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()

图表示例


推荐阅读