[英]Pandas Average If in Python : Combining groupby mean with conditional statement
I've looked through the forums and can't seem to figure this out.我浏览了论坛,似乎无法弄清楚这一点。 I have the following data.
我有以下数据。 I assume the answer lies in the "groupby" function but I can't seem to work it out.
我认为答案在于“groupby”功能,但我似乎无法解决。
Date Hour Value 3DAverage
1/1 1 57 53.33
1/1 2 43 42.33
1/1 3 44 45.33
1/2 1 51 ...
1/2 2 40 ...
1/2 3 42 ...
1/3 1 56 ...
1/3 2 42
1/3 3 48
1/4 1 53
1/4 2 45
1/4 3 46
1/5 1 56
1/5 2 46
1/5 3 48
1/5 4 64 *
1/6 1 50
1/6 2 41
1/6 3 42
1/7 1 57
1/7 2 43
1/7 3 45
1/8 1 58
1/8 2 49
1/8 3 41
1/9 1 53
1/9 2 46
1/9 3 47
1/10 1 58
1/10 2 49
1/10 3 40
What I am trying to do is add the "3DAverage" column.我想要做的是添加“3Daverage”列。 I would like this column to produce an average of the "Value" column for the PRIOR 3 corresponding hour values.
我希望此列为 PRIOR 3 对应的小时值生成“值”列的平均值。 I want to fill this column down for the entire series .
我想为整个系列填写此列。 For example, the value 53.33 is an average of the value for hour 1 on 1/2, 1/3, and 1/4.
例如,值 53.33 是 1/2、1/3 和 1/4 小时 1 的平均值。 I would like this to continue down the column using only the prior 3 values for each "HourValue".
我希望这仅使用每个“HourValue”的前 3 个值继续向下列。
Also, please note that there are instances such as 1/5 hour 4. Not all dates have the same number of hours, so I am looking for the last 3 hour values for dates in which those hours exist.另外,请注意有 1/5 小时 4 之类的实例。并非所有日期的小时数都相同,因此我正在寻找存在这些小时数的日期的最后 3 小时值。
I hope that makes sense.我希望这是有道理的。 Thanks so much in advance for your help !
非常感谢您的帮助!
You can try rolling mean 你可以试试滚动的意思
df['3D Average'] = df.iloc[::-1].groupby('Hour').Value.rolling(window = 3).mean()\
.shift().sort_index(level = 1).values
You can groupby
on Date column and do the following: 您可以在Date列上进行
groupby
并执行以下操作:
df['3DAverage'] = df['Hour'].map(df.groupby('Hour').apply(lambda x: x.loc[x['Date'].isin(['1/2','1/3','1/4']),'Value'].mean()))
df.head(6)
Date Hour Value 3DAverage
0 1/1 1 57 53.333333
1 1/1 2 43 42.333333
2 1/1 3 44 45.333333
3 1/2 1 51 53.333333
4 1/2 2 40 42.333333
5 1/2 3 42 45.333333
有谁知道我应该如何修改上面的 2 个答案以与 2 groupby 一起使用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.