1

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)
syntheso
  • 437
  • 3
  • 17
  • 3
    Possible duplicate of [Count occurrences of items in Series in each row of a DataFrame](https://stackoverflow.com/questions/24516361/count-occurrences-of-items-in-series-in-each-row-of-a-dataframe) – roganjosh Nov 02 '18 at 11:04
  • @roganjosh, I'm sure this must be a dup (though I can't find it right now), but I don't think that's the one. – jpp Nov 02 '18 at 11:05

2 Answers2

4

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
Mohamed Thasin ah
  • 10,754
  • 11
  • 52
  • 111
2

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)
jpp
  • 159,742
  • 34
  • 281
  • 339