在一个 pandas 数据框中,平均几个星期的平均时间在几天之内 [英] Getting the average of a certain hour on weekdays over several years in a pandas dataframe
问题描述
我有几年以下格式的小时数据框:
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
有谁知道在大熊猫中获得这个?
推荐答案
注意:现在该系列有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 索引你可以这样做:
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):
假设日期/时间是索引*,您可以在 groupby :
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屋!