syntheso
syntheso

Reputation: 447

Sum number of occurences of string per row

I have been trying to search an answer for this and I can't find one - I must be misunderstanding something.

I simply want to sum the number of times a string ("True") occurs per row. The desired output is below:

d1 = {'score': ['True', 'True', 'False'], 'score2': ['False', 'True', 'True'], 'total': [1, 2, 1]}
df1 = pd.DataFrame(data=d1)

Upvotes: 1

Views: 92

Answers (2)

Mohamed Thasin ah
Mohamed Thasin ah

Reputation: 11192

try this,

df1['total']= df1.eq('True').sum(axis=1)

If df is boolean try this,

df1['total']= df1.eq(True).sum(axis=1)

For More cleaner way,

df1['total']= df1.sum(axis=1)

Output:

   score score2  total
0   True  False      1
1   True   True      2
2  False   True      1

Upvotes: 4

jpp
jpp

Reputation: 164683

String values: eq + sum

df1['total'] = df1[['score', 'score2']].eq('True').sum(1)

print(df1)

   score score2  total
0   True  False      1
1   True   True      2
2  False   True      1

Boolean values: sum

No Boolean test needs to be performed in this case:

df1['total'] = df1[['score', 'score2']].sum(1)

Upvotes: 2

Related Questions