5

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
1
  • df.eq(1).sum(axis=1) Commented Oct 25, 2019 at 9:15

2 Answers 2

6

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)
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.