简体   繁体   中英

Pandas - How to get the number of occurrences for each value in a column

I have this csv file called fifa, and it is a record of football player stats.

There is a column, called 'preferred foot' (to kick the ball with), and its values could be either 'left' or 'right' foot only for each record (player).

So what is the fastest way to get a count of the number of players with a right preferred foot, and a left preferred foot.

Example table:

# Foot
1 Right
2 Left
3 Left
4 Right
5 Right
6 Left
7 Right
8 Right

And from this table, I need the number of players for each of the possible values in the column, so in turn, the above table would be used to create this table.

Foot    Number
Right   5
Left    3

Please make this general, like what if I were to add multiple values other than left or right to the possible values of the column. Don't limit it to only two possible values for the column.

You can use value_counts() and reset_index() methods like

new_df = df["preferred foot"].value_counts().reset_index(name="Numbers")

Value_counts method counts unique values, and reset_index resets the index to count column (here we name it Numbers)

您可以使用分组依据和按计数聚合

df.groupby(['Foot']).agg({'player_id': ['count']})

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