count occurrences of one variable grouped by another python

Solutions on MaxInterview for count occurrences of one variable grouped by another python by the best coders in the world

showing results for - "count occurrences of one variable grouped by another python"
Sofia
17 Jul 2019
1>>> data = pd.DataFrame({'user_id' : ['a1', 'a1', 'a1', 'a2','a2','a2','a3','a3','a3'], 'product_id' : ['p1','p1','p2','p1','p1','p1','p2','p2','p3']})
2>>> count_series = data.groupby(['user_id', 'product_id']).size()
3>>> count_series
4user_id  product_id
5a1       p1            2
6         p2            1
7a2       p1            3
8a3       p2            2
9         p3            1
10dtype: int64
11>>> new_df = count_series.to_frame(name = 'size').reset_index()
12>>> new_df
13  user_id product_id  size
140      a1         p1     2
151      a1         p2     1
162      a2         p1     3
173      a3         p2     2
184      a3         p3     1
19>>> new_df['size']
200    2
211    1
222    3
233    2
244    1
25Name: size, dtype: int64