0

Here is an example of my DataFrame

  user    workflow    device     location  date 
  A         top         Mac      SF        1/1/19
  B         left        Win      SA        1/1/19
  A         right       Mac      SF        1/5/19
  C         left        iphone   LA        1/7/19
  D         left        pixel    BO        1/20/19
  C         bottom      iphone   LA        1/21/19

I want to transform the DF to look like this:

 User top bottom left right Mac Win iphone pixel SF  SA   LA  BO
 A     1   0     0      1   1   0     0     0     2   0   0    0
 B     0   0     1      0   0   1     0     0     0   1   0    0
 C     0   1     1      0   0   0     2     0     0   0   2    0
 D     0   0     1      0   0   0     0     1     0   0   0    1

How would one do that using Pandas?

1 Answer 1

1

Using str.get_dummies after stack

s=df.set_index('user').stack().str.get_dummies().sum(level=0)
s  
      BO  LA  Mac  SA  SF  Win  bottom  iphone  left  pixel  right  top
user                                                                   
A      0   0    2   0   2    0       0       0     0      0      1    1
B      0   0    0   1   0    1       0       0     1      0      0    0
C      0   2    0   0   0    0       1       2     1      0      0    0
D      1   0    0   0   0    0       0       0     1      1      0    0
Sign up to request clarification or add additional context in comments.

12 Comments

what if I had other columns I am not using in the DataFrame. How would I still output the same result?
@user5844628 I am not get the , what you mean other columns but not in the data frame ?
please see updated DateFrame. I add a date column but I do not desire to use that in my transformed counts
@user5844628 I think I get you , df.drop('date',1).set_index('user').stack().str.get_dummies().sum(level=0)
Thanks! What if you had 100+ columns you are not using. Is there an easier way to drop those without specifically calling the column names out as you are doing here?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.