4

For example, I have a DataFrame named a. I want to count the element of each row.

import numpy as np
a=pd.DataFrame({'A1':['financial','game','game'],'A2':['social','food','sport'],'A3':['social','sport','game']})

Input:

          A1      A2      A3
0  financial  social  social
1       game    food   sport
2       game   sport    game

Expected:

    financial  food  game  social  sport
0          1      0     0       2      0
1          0      1     1       0      1
2          0      0     2       0      1

Hopefully for help, thanks!

1 Answer 1

6

Use pandas.get_dummies with sum:

df = pd.get_dummies(a, prefix_sep='', prefix='').sum(axis=1, level=0)
print (df)
   financial  game  food  social  sport
0          1     0     0       2      0
1          0     1     1       0      1
2          0     2     0       0      1

Or stack with SeriesGroupBy.value_counts and Series.unstack:

df = a.stack().groupby(level=0).value_counts().unstack(fill_value=0)
print (df)
   financial  food  game  social  sport
0          1     0     0       2      0
1          0     1     1       0      1
2          0     0     2       0      1
Sign up to request clarification or add additional context in comments.

Comments

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.