Reputation: 31
Image A is my dataframe with two columns which as multiple values, I want convert this val column as my header for columns as shown in Image B and add count of values for each user. I tried using pandas groupby and count but not able to get expected result.
lst = ['UserA', 'UserB', 'UserC', 'UserD','UserB', 'UserC']
lst2 = ['X', 'Y', 'Z', 'Y','X','Z']
dm = pd.DataFrame(list(zip(lst, lst2)), columns =['Name', 'val'])
dm['count']= 1
dm.groupby(['Name','val']).count()
Upvotes: 2
Views: 846
Reputation: 153460
Add unstack
:
dm.groupby(['Name','val']).count()['count'].unstack('val', fill_value='')
Output:
val X Y Z
Name
UserA 1
UserB 1 1
UserC 2
UserD 1
Upvotes: 3