Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

count occurrences of one variable grouped by another python

>>> 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']})
>>> count_series = data.groupby(['user_id', 'product_id']).size()
>>> count_series
user_id  product_id
a1       p1            2
         p2            1
a2       p1            3
a3       p2            2
         p3            1
dtype: int64
>>> new_df = count_series.to_frame(name = 'size').reset_index()
>>> new_df
  user_id product_id  size
0      a1         p1     2
1      a1         p2     1
2      a2         p1     3
3      a3         p2     2
4      a3         p3     1
>>> new_df['size']
0    2
1    1
2    3
3    2
4    1
Name: size, dtype: int64
Comment

PREVIOUS NEXT
Code Example
Python :: python count how many times a word appears in a string 
Python :: python first 
Python :: open multiple plots python 
Python :: putting in text in python 
Python :: set time complexity python 
Python :: pysimplegui get value from textbox 
Python :: Python re.subn() 
Python :: how to get a specific character in a string on number python 
Python :: pandas find fifth caracter in field and change cell based on that number 
Python :: binary search tree in python 
Python :: init array in numpy 
Python :: not using first row as index pandas 
Python :: convert 2 lists into dictionary 
Python :: how to find duplicate strings in a list of string python function 
Python :: pivot table but keep nan 
Python :: check package is installed by conda or pip environment 
Python :: set remove in python 
Python :: How to Loop Through Tuples using for loop in python 
Python :: plot scattered dataframe 
Python :: quicksort algorithm in python 
Python :: how to convert str to int python 
Python :: Returns the first row as a Row 
Python :: command for python shell 
Python :: how to check if digit in int python 
Python :: Replace an item in a python list 
Python :: pandas weighted average groupby 
Python :: convert a list to tuple 
Python :: python - input: integer 
Python :: how to schedule python script in windows 
Python :: Run Django application using Gunicorn 
ADD CONTENT
Topic
Content
Source link
Name
2+9 =