【问题标题】:Consecutive zeros count (multi-index)连续零计数(多索引)
【发布时间】:2020-12-12 11:35:47
【问题描述】:

我正在尝试计算连续的零:

每当binary column 上出现非零值时,Consec Column 的计数就会重新开始

     binary consec
1       1      0
2       0      1
3       0      2
4       0      3
5       0      4
5       1      0
6       0      1
7       0      2
8       1      0

this Solution,我可以做到

df = pd.DataFrame({"binary": [0,1,1,1,0,0,1,1,0]})
df["consec"] = df["binary"].groupby((df["binary"] != 0).cumsum()).cumcount()

   binary  consec
1       1      0
2       0      1
3       0      2
4       0      3
5       0      4
5       1      0
6       0      1
7       0      2
8       1      0

但是,我想对这样的多索引情况做同样的事情:

import pandas as pd
df = pd.DataFrame({"gp_1": [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2], "gp_2": [1,1,1,1,1,1,1,1,1,3,3,3,3,4,4,4,4,4], "binary": [0,1,1,1,0,0,1,1,0, 0,1,1,1,0,0,1,1,0]})

预期输出:

  gp_1 gp_2 binary  consec
0   1   1   0         1  
1   1   1   1         0
2   1   1   1         0
3   1   1   1         0
4   1   1   0         1
5   1   1   0         2
6   1   1   1         0
7   1   1   1         0
8   1   1   0         1
9   2   3   0         1
10  2   3   1         0
11  2   3   1         0
12  2   4   0         1
13  2   4   0         2
14  2   4   0         3
15  2   4   1         0
16  2   4   1         0
17  2   4   0         1

【问题讨论】:

  • 您的预期输出是什么?请解释一下多索引情况是什么意思
  • 对不起,我的错误。我刚刚发布了一个更新的帖子。
  • .groupby((df["binary"] == 0)改成.groupby(["gp_1", "gp_2", df["binary"] == 0])?
  • 正在执行 'df.groupby(["gp_1", "gp_2", df["binary"] != 0]).cumsum().cumcount()' 或 df["binary"] .groupby(["gp_1", "gp_2", df["binary"] != 0]).cumsum().cumcount() 导致错误

标签: pandas numpy


【解决方案1】:

让我们试试

df.groupby([df.gp_1,df.gp_2,df.binary.diff().ne(0).cumsum()]).cumcount().add(1).where(df.binary==0,0)
Out[149]: 
0     1
1     0
2     0
3     0
4     1
5     2
6     0
7     0
8     1
9     1
10    0
11    0
12    1
13    2
14    3
15    0
16    0
17    1
dtype: int64

【讨论】:

    猜你喜欢
    • 2019-03-16
    • 2020-05-11
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    相关资源
    最近更新 更多