简体   繁体   English

熊猫数据框中的平均值

[英]Mean of values in pandas dataframe

I have a dataframe, for example: 我有一个数据框,例如:

Val1    Val2
1        4
2        10
2        5
1        7
2        0
1        20

I want to get a mean of all numbers from Val2 that have Val1 value equal to 1 (in the same row). 我想从Val2中获得所有均值,其中Val1值等于1(在同一行中)。 How can I do that without using loop? 不使用循环怎么办?

你可以试试

df.groupby(['Val1'])['Val2'].mean()

I am supposing you just want the mean as a simple float number. 我想您只是想将平均值作为一个简单的浮点数。 In this case, you can do: 在这种情况下,您可以执行以下操作:

df[df["Val1"] == 1]["Val2"].mean()

其他答案也应该提供正确的答案,但是我认为最惯用的方法是: df.loc[df['Val1']==1, 'Val2'].mean()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM