python - Pandas 根据另一列的条件重置 cumsum()

标签 python python-3.x pandas

我有一个名为“on”的列,其中包含一系列 0 和 1:

d1 = {'on': [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0]}
df = pd.DataFrame(d1)
我想创建一个名为“值”的新列,以便它进行累积计数 cumsum()仅当“on”列的“1”打开并在“on”列显示为零时从零重新计数。
我尝试使用 cumsum() 的组合和 np.where但我没有得到我想要的如下:
df['value_try'] = df['on'].cumsum()
df['value_try'] = np.where(df['on'] == 0, 0, df['value_try'])
试图:
    on  value_try
0    0          0
1    0          0
2    0          0
3    1          1
4    1          2
5    1          3
6    0          0
7    0          0
8    1          4
9    1          5
10   0          0
我想要的输出是:
    on  value
0    0      0
1    0      0
2    0      0
3    1      1
4    1      2
5    1      3
6    0      0
7    0      0
8    1      1
9    1      2
10   0      0

最佳答案

您可以通过检查 on 的值是否设置连续的 0 或 1 组。等于前一行的 .shift() 并通过 .Series.cumsum() 获取组号.然后对于每个组使用 .Groupby.cumsum() 获取组内的值。

g = df['on'].ne(df['on'].shift()).cumsum()
df['value'] = df.groupby(g).cumsum()
结果:
print(df)

    on  value
0    0      0
1    0      0
2    0      0
3    1      1
4    1      2
5    1      3
6    0      0
7    0      0
8    1      1
9    1      2
10   0      0

关于python - Pandas 根据另一列的条件重置 cumsum(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67973031/

相关文章:

python - 在 matplotlib 中传递用于绘图的元组会在第 10 行抛出 "Tuple Object is not callable"错误。 3个

python pandas如何按 block 读取csv文件

python - 在 Python 中打开 .h5 文件

python - Leetcode 424.最长重复字符替换: Right Pointer Incrementation

python - Pandas - 根据 A 列中的值访问 B 列中的值

python - 困惑为什么这段代码不会打印任何内容

python - 将主题分布(主题模型的结果)添加到 Pandas 数据框

python - 断管错误 selenium webdriver,当命令之间存在间隙时?

python - 替换所有脚本 src 属性的正则表达式

python - IronPython + Wpf 上的按钮单击事件