python - 计算 python 中连续 1 的个数

标签 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

最佳答案

仅在所有列中使用 if always 10sum:

 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/

相关文章:

python - 将 pandas MultiIndex DataFrame 从按行转换为按列

r - 根据R中每列中的每个值创建一个计数表

python - 如何将两个 ModelForms 组合在一个 View 中,并以任意顺序显示字段?

Python pandas read_sql 返回生成器对象

python - 生成器在 Python 中有什么类型签名?

Python:将代码应用于整个数据框列

python - 使用非唯一索引 reshape DataFrame

python - 将分类列添加到预测模型中

django - django中按字段类型统计数据库条目

mysql - 如何编写 sql 查询以按类型选择和分组以及按类型计数?