注意:现在Series有了dt访问器,日期是否为索引不那么重要,但Date/Time仍然需要是datetime64类型。
更新:你可以更直接地进行分组(无需lambda):
In [21]: df.groupby([df["Date/Time"].dt.year, df["Date/Time"].dt.hour]).mean()
Out[21]:
Value
Date/Time Date/Time
2010 0 60
1 50
2 52
3 49
In [22]: res = df.groupby([df["Date/Time"].dt.year, df["Date/Time"].dt.hour]).mean()
In [23]: res.index.names = ["year", "hour"]
In [24]: res
Out[24]:
Value
year hour
2010 0 60
1 50
2 52
3 49
如果它是一个 datetime64 的 索引,你可以这样做:
In [31]: df1.groupby([df1.index.year, df1.index.hour]).mean()
Out[31]:
Value
2010 0 60
1 50
2 52
3 49
旧回答(速度较慢):
假设日期/时间是索引*,您可以在 groupby 中使用映射函数:
In [11]: year_hour_means = df1.groupby(lambda x: (x.year, x.hour)).mean()
In [12]: year_hour_means
Out[12]:
Value
(2010, 0) 60
(2010, 1) 50
(2010, 2) 52
(2010, 3) 49
要创建一个更有用的索引,您可以从元组中创建MultiIndex:
In [13]: year_hour_means.index = pd.MultiIndex.from_tuples(year_hour_means.index,
names=['year', 'hour'])
In [14]: year_hour_means
Out[14]:
Value
year hour
2010 0 60
1 50
2 52
3 49
* 如果没有设置过索引,请先使用 set_index
:
df1 = df.set_index('Date/Time')
as_index=False
来覆盖它。重新阅读这个问题后,我会做一些不同的事情。更新了一个更好的方法来完成这个任务(它恰好可以直接创建多级索引)。 - Andy Hayden