[英]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.我有一个名为 fifa 的 csv 文件,它是足球运动员统计数据的记录。
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.请将此设为通用,就像我要向列的可能值添加除 left 或 right 之外的多个值一样。 Don't limit it to only two possible values for the column.
不要将它限制为只有两个可能的列值。
You can use value_counts()
and reset_index()
methods like您可以使用
value_counts()
和reset_index()
方法,例如
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) Value_counts 方法对唯一值进行计数,reset_index 将索引重置为计数列(这里我们将其命名为 Numbers)
您可以使用分组依据和按计数聚合
df.groupby(['Foot']).agg({'player_id': ['count']})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.