如何计算位于数字1之间的零的数量

huangapple go评论136阅读模式
英文:

How to count the number of zeros if they lie between ones

问题

Sure, here are the translations of the code-related parts:

我有一个数据框架

ID   A  B  C
60   0  1  1
120  0  1  1
180  0  1  1
240  0  0  0
300  0  0  0 
360  1  1  0
420  1  1  1
480  0  0  0
540  0  0  0 
600  0  0  0
660  0  0  0
720  1  1  1
780  1  0  1
840  0  0  0
900  0  0  0

如何计算仅在1之间的零的数量

在这个例子中,答案应该是A中的[4],B中的[2,4],C中的[3,4]

请帮助我。

我已经看到这个选项,但它不适用,因为它计算一行中的所有零。我需要只计算1之间的零。请帮助。

英文:

I have dataframe

ID   A  B  C
60   0  1  1
120  0  1  1
180  0  1  1
240  0  0  0
300  0  0  0 
360  1  1  0
420  1  1  1
480  0  0  0
540  0  0  0 
600  0  0  0
660  0  0  0
720  1  1  1
780  1  0  1
840  0  0  0
900  0  0  0 

How to count the number of zeros only between 1

in this example, the answer should be [4] in A, [2,4] in B, [3,4] in C

Could you help me, please?

i have seen this option, but it does not fit, since it counts all zeros in a row. And I need to count zeros only between 1. Please help.

答案1

得分: 3

你可以尝试类似于bfillffill,然后对结果进行groupby操作。

s = (df.mask(df==0).ffill() == df.mask(df==0).bfill()) & (df==0)
s = s.apply(lambda x: x[x].groupby((~x).cumsum()).count().tolist())
ID        []
A        [4]
B     [2, 4]
C     [3, 4]
dtype: object
英文:

You can try something like bfill and ffill then groupby the result

s = (df.mask(df==0).ffill() == df.mask(df==0).bfill()) & (df==0)
s = s.apply(lambda x : x[x].groupby((~x).cumsum()).count().tolist())
ID        []
A        [4]
B     [2, 4]
C     [3, 4]
dtype: object

答案2

得分: 0

以下是翻译好的内容:

您还可以使用 itertools.groupby

from itertools import groupby

df.apply(lambda s: [g for k,g in [(k, len(list(g))) 
                                  for k,g in groupby(s, lambda x: x==0)
                                 ][1:-1] if k])

输出:

ID        []
A        [4]
B     [2, 4]
C     [3, 4]
dtype: object
英文:

You can also use itertools.groupby:

from itertools import groupby

df.apply(lambda s: [g for k,g in [(k, len(list(g))) 
                                  for k,g in groupby(s, lambda x: x==0)
                                 ][1:-1] if k])

Output:

ID        []
A        [4]
B     [2, 4]
C     [3, 4]
dtype: object

huangapple
  • 本文由 发表于 2023年8月11日 02:36:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定