To count the number of 1's in a row in python

Viewed 1258

I have a dataframe with column names ranging from P1 to P10

  p1 p2 p3  p4  p5 
    0   0  0  1    1
    0   0  0  0    0
    1   1  1  1    1

the total number of 1 has to be displayed at the end of the row 
example : first row = 2 
second row = 0
third row = 5
2 Answers

Use if always 1 and 0 values in all columns only sum:

 df['new'] = df.sum(axis=1)

If possible another values then first compare for boolean mask and then count Trues by sum:

 df['new'] = df.eq(1).sum(axis=1)

You can also use Numpy functions.

In the case like yours (only 1 and 0), you can use:

df['sum'] = np.count_nonzero(df, axis=1)

But if you have also other numbers, use:

df['sum'] = np.count_nonzero(df == 1, axis=1)
Related