gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:55 25 4
gpt4 key购买 nike

我有一个列名范围从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com