pandas 熊猫计算一列中值的出现次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53100242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:07:31  来源:igfitidea点击:

pandas count number of occurrences of values in one column

pythonpandas

提问by mshabeeb

I have a long dataframe with only one column and around 800k rows. my data frame looks like this

我有一个只有一列和大约 80 万行的长数据框。我的数据框看起来像这样

54
53
53
53
53
...
0
0
0

So what I need is to count the number of occurrences of each value and saving this into a dataframe so the result would be something like this

所以我需要的是计算每个值的出现次数并将其保存到数据帧中,这样结果就会是这样的

54 1
53 1000
52 800
...
0 100000

I have tried using df.groupby(0)but it only returns an object. How can I get a two-column dataframe (or 1 column and a row-index showing the values)?

我试过使用,df.groupby(0)但它只返回一个对象。如何获得两列数据框(或 1 列和显示值的行索引)?

回答by Franco Piccolo

Use value_countsand to_frame:

使用value_countsto_frame

df = pd.DataFrame([1,2,4,5,5], columns=['values'])
df['values'].value_counts().to_frame().reset_index().rename(columns={'index':'values', 'values':'count'})

 values count
0   5   2
1   4   1
2   2   1
3   1   1