rosefun
rosefun

Reputation: 1867

python: How to count the elements of a row?

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!

Upvotes: 4

Views: 1623

Answers (1)

jezrael
jezrael

Reputation: 863531

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

Upvotes: 6

Related Questions