要在python中连续计算1的数量

时间:2019-10-25 09:14:22

标签: python pandas count

我有一个数据框,其列名的范围从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

2 个答案:

答案 0 :(得分:4)

仅在所有列中的10值中使用sum

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

如果可能的话,请先比较布尔值掩码,再将True乘以sum

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

答案 1 :(得分:0)

您还可以使用 Numpy 函数。

在像您这样的情况下(仅 1 0 ),您可以使用:

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

但是如果您还有其他数字,请使用:

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