简体   繁体   中英

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.

Using Python-Pandas, I have tried:

INPUT:

df.groupby('number_of_horses').winner.count()

OUTPUT:

在此处输入图像描述

The table above is not the desired output.

The desired output is:

在此处输入图像描述

Note that the 'winner' column is only counted when the value is TRUE.

Here you go:

df[df.winner == True].groupby('number_of_horses').winner.count().reset_index()                                                                                                                                         

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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