在 Pandas 数据框中获得几年内工作日某个小时的平均值 [英] Getting the average of a certain hour on weekdays over several years in a pandas dataframe

查看:25
本文介绍了在 Pandas 数据框中获得几年内工作日某个小时的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多年来,我有以下格式的每小时数据帧:

I have an hourly dataframe in the following format over several years:

Date/Time            Value
01.03.2010 00:00:00  60
01.03.2010 01:00:00  50
01.03.2010 02:00:00  52
01.03.2010 03:00:00  49
.
.
.
31.12.2013 23:00:00  77

我想对数据求平均值,这样我就可以得到每年第 0 小时、第 1 小时……第 23 小时的平均值.

I would like to average the data so I can get the average of hour 0, hour 1... hour 23 of each of the years.

所以输出应该看起来像这样:

So the output should look somehow like this:

Year Hour           Avg
2010 00              63
2010 01              55
2010 02              50
.
.
.
2013 22              71
2013 23              80

有谁知道如何在 Pandas 中获得这个?

推荐答案

注意:既然 Series 有 dt 访问器,日期是索引就不那么重要了,尽管日期/时间仍然需要是 datetime64.

更新:您可以更直接地进行 groupby(没有 lambda):

Update: You can do the groupby more directly (without the 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 index 你可以这样做:

If it's a datetime64 index you can do:

In [31]: df1.groupby([df1.index.year, df1.index.hour]).mean()
Out[31]:
        Value
2010 0     60
     1     50
     2     52
     3     49

<小时>

旧答案(会更慢):


Old answer (will be slower):

假设日期/时间是索引*,您可以在 中使用映射函数分组:

Assuming Date/Time was the index* you can use a mapping function in the 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:

For a more useful index, you could then create a MultiIndex from the tuples:

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:

* if not, then first use set_index:

df1 = df.set_index('Date/Time')

这篇关于在 Pandas 数据框中获得几年内工作日某个小时的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆