我有一个列名范围从 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
最佳答案
仅在所有列中使用 if always 1
和 0
值 sum
:
df['new'] = df.sum(axis=1)
如果可能,另一个值然后首先比较 bool 掩码,然后通过 sum
计算 True
:
df['new'] = df.eq(1).sum(axis=1)
关于python - 计算 python 中连续 1 的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58555549/