简体   繁体   English

Pandas - 如何获取列中每个值的出现次数

[英]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.

相关问题 Python / Pandas:如何在数据框中的每一列中查找特定值的出现次数? - Python/Pandas: How to find the number of occurrences of a specific value in each column a data frame? 如何计算一列列表中每个唯一值的出现次数 Pandas - How to count occurrences of each unique value within a column of lists Pandas pandas groupby 和列的每个值出现的百分比 - pandas groupby and percentage of occurrences of each value of a column 熊猫计算列中每个值的出现次数 - Pandas count the occurrences of each value in column 如何获得 pandas groupby 中值的最小出现次数 - How to get minimum number of occurrences of value in pandas groupby 如何使用 pandas 计算另一列中每个值在一列中出现的次数? - How to count number of occurrences of value in one column per value in other column using pandas? pandas:计算列表中每个元素在列表列中唯一出现的次数 - pandas: count the number of unique occurrences of each element of list in a column of lists 有没有办法在另一列的列中找到每个值的出现次数? - Is there a way to find the number of occurrences of each value in a column in another column? 熊猫计算范围之间每个值的出现次数 - Pandas count number of occurrences of each value between ranges Pandas-如何获取另一列中每个对应值的行数 - Pandas- How to get number of times row occurs for each corresponding value in another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM