[英]Pandas groupby - when column is a certain value
For the following table:对于下表:
I would like to use the groupby function with 'number_of_horses' and show a count for the 'TRUE' values in the 'winner' column.我想将 groupby function 与“number_of_horses”一起使用,并在“winner”列中显示“TRUE”值的计数。
Using Python-Pandas, I have tried:使用 Python-Pandas,我尝试过:
INPUT:输入:
df.groupby('number_of_horses').winner.count()
OUTPUT: OUTPUT:
The table above is not the desired output.上表不是所需的 output。
The desired output is:所需的 output 是:
Note that the 'winner' column is only counted when the value is TRUE.请注意,仅当值为 TRUE 时才会计算“获胜者”列。
Here you go:这里是 go:
df[df.winner == True].groupby('number_of_horses').winner.count().reset_index()
Output Output
number_of_horses winner
0 2 2
1 3 6
If the winner
column is a string, then use df.winner == "TRUE"
as your filtering criteria如果
winner
列是字符串,则使用df.winner == "TRUE"
作为过滤条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.