Getting the average of a certain hour on weekdays over several years in a pandas dataframe(在 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 数据框中获得几年内工作日某个小时的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Pandas 数据框中获得几年内工作日某个小时的平


- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01