![](/img/trans.png)
[英]Pandas - Calculate average of columns with condition based on values in other columns
[英]How to average certain values of a column based on other columns condition in pandas
我有一个像这样的数据框:
Index Date Type Value
0 01/01/2010 A 10
1 01/01/2010 B 15
2 01/01/2010 B 25
3 01/01/2010 A 12
4 01/02/2010 A 9
5 01/02/2010 B 17
6 01/02/2010 B 20
7 01/02/2010 A 8
我想创建一个新列,以便针对每一行对基于类型和基于日期的值取平均值,因此对于给定的日期,所有具有类型A的行都将具有相同的平均值,并且对于类型B将具有相同的平均值。 2010年1月1日,所有类型A的丝束均为(10 + 12)/ 2 = 11,所有类型B的丝束均为(15 + 25)/ 2 = 20:
Index Date Type Value Value2
0 01/01/2010 A 10 11
1 01/01/2010 B 15 20
2 01/01/2010 B 25 20
3 01/01/2010 A 12 11
4 01/02/2010 A 9 8.5
5 01/02/2010 B 17 13.5
6 01/02/2010 B 20 13.5
7 01/02/2010 A 8 8.5
您可能想要groupby
和transform
(尽管我不确定您期望的输出中为什么01/02/2010
类型B
是13.5
,我认为应该是18.5
, 即 17和20的平均值):
df['Value2'] = df.groupby(['Type','Date']).Value.transform('mean')
>>> df
Index Date Type Value Value2
0 0 01/01/2010 A 10 11.0
1 1 01/01/2010 B 15 20.0
2 2 01/01/2010 B 25 20.0
3 3 01/01/2010 A 12 11.0
4 4 01/02/2010 A 9 8.5
5 5 01/02/2010 B 17 18.5
6 6 01/02/2010 B 20 18.5
7 7 01/02/2010 A 8 8.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.