Harishchandra
Harishchandra

Reputation: 31

Convert column as column header with count of column values

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

Image A, This is my dataset

Image B, this is expected output

Upvotes: 2

Views: 846

Answers (1)

Scott Boston
Scott Boston

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

Related Questions