在python中计算一行中1的数量

Sca*_*Sca 4 python count pandas

我有一个列名从 P1 到 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
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 6

仅使用 if always10所有列中的值sum

 df['new'] = df.sum(axis=1)
Run Code Online (Sandbox Code Playgroud)

如果可能,另一个值然后首先比较布尔掩码,然后Truesum以下方式计算s :

 df['new'] = df.eq(1).sum(axis=1)
Run Code Online (Sandbox Code Playgroud)