Reputation: 95
I have a DatetimeIndex
indexed Series s1 like
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
and want mean()
for each day of the week. Then I want to get day_name()
of the index to draw a graph label but I cannot since DatetimeIndex
now becomes int.
g1 = s1.groupby(s1.index.dayofweek).mean()
----> 3 g1.index.day_name()
AttributeError: 'Int64Index' object has no attribute 'day_name'
What is the smartest workaround?
Upvotes: 1
Views: 149
Reputation: 120401
Group by day_name
:
>>> s1.groupby(s1.index.day_name()).mean()
Tuesday 12271611.0
Name: time, dtype: float64
Graph example:
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()
Upvotes: 1
Reputation: 71570
Try this:
>>> s1.groupby(s1.index.dayofweek).transform('mean').index.day_name().drop_duplicates()
Index(['Tuesday'], dtype='object')
>>>
Upvotes: 0