简体   繁体   中英

pandas count number of occurrences of values in one column

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

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)?

Use value_counts and to_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

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