python - 一旦满足条件,累加 1 并重置为 0

标签 python pandas machine-learning

目前我在下面有一个数据集,如果 ColA 为 0,我尝试累加该值,而如果 ColA 再次为 1,则将值重置为 0(再次重新开始计数)。

ColA  
 1        
 0        
 1        
 1        
 0        
 1        
 0         
 0        
 0        
 1        
 0        
 0        
 0        

我的预期结果如下。

ColA  Accumulate
 1        0
 0        1
 1        0 
 1        0 
 0        1
 1        0
 0        1 
 0        2 
 0        3
 1        0
 0        1
 0        2
 0        3

我目前使用的代码

test['Value'] = np.where ( (test['ColA']==1),test['ColA'].cumsum() ,0)


ColA   Value
 1        0
 0        1
 1        0 
 1        0 
 0        2
 1        0
 0        3 
 0        4 
 0        5
 1        0
 0        6
 0        7
 0        8

最佳答案

使用cumsum如果性能很重要:

a = df['ColA'] == 0
cumsumed = a.cumsum()
df['Accumulate'] = cumsumed-cumsumed.where(~a).ffill().fillna(0).astype(int)

print (df)
    ColA  Accumulate
0      1           0
1      0           1
2      1           0
3      1           0
4      0           1
5      1           0
6      0           1
7      0           2
8      0           3
9      1           0
10     0           1
11     0           2
12     0           3

关于python - 一旦满足条件,累加 1 并重置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50490864/

相关文章:

python - 我们如何使用 pandas 在 python 中使用 Coalesce 来处理多个数据帧

python - 如何在 jinja2 中对危险的未经处理的输入进行 html 转义?

python - 使用 PyEZ 在 Juniper 路由器中执行 vty 命令

python - 无法在 Python 3.x 中安装 paho-mqtt

python - numpy 函数如何在内部对 pandas 对象进行操作?

python - 使用 Pandas 检查列值是否位于某一特定列中

machine-learning - 在 CNN 中 Dropout 之前堆叠多个 Conv2D 层背后的直觉

machine-learning - 使用大量数据偏向某一类别来预测类别

machine-learning - 朴素贝叶斯模型

python - 根据从列表中选择的项目过滤掉帧