Unique values count in a dataframe

Viewed 39

I have data like this:

Date | Location  | Item
-----------------------
1    | x         | a 
1    | x         | b 
1    | x         | a 
2    | b         | a 

and I'd like to extract unique values of rows and add a column for number of occurence

I tried this command but it failed:

p=df3.groupby(['date', 'location', 'item']).count()

Result=

Date | Location  | Item | Occurences
------------------------------------
1    | x         | a    | 2
1    | x         | b    | 1 
2    | b         | a    | 1
1 Answers

Use .size():

df.groupby(['Date', 'Location', 'Item']).size().rename('Ocurrences').to_frame().reset_index()

    Date    Location    Item    Ocurrences
0   1           x          a    2
1   1           x          b    1
2   2           b          a    1
Related