pandas count number of occurrences of values in one column

Viewed 8868

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

1 Answers

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
Related