首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Dataframe中计数连续零的数目

在Dataframe中计数连续零的数目
EN

Stack Overflow用户
提问于 2017-07-24 13:12:03
回答 3查看 4.8K关注 0票数 0

我想在下面显示的数据中计数连续零的数目,请帮助

代码语言:javascript
运行
复制
  DEC  JAN  FEB  MARCH  APRIL  MAY        consecutive zeros
0    X    X    X      1      0    1              0
1    X    X    X      1      0    1              0
2    0    0    1      0      0    1              2
3    1    0    0      0      1    1              3
4    0    0    0      0      0    1              5
5    X    1    1      0      0    0              3
6    1    0    0      1      0    0              2
7    0    0    0      0      1    0              4
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-07-24 15:23:40

这是我的两分钱。

假设所有其他非零元素都是1,那么您将有一个二进制代码。现在您需要做的就是找到“最大间隔”,在这里没有从0开始的位翻转。

我们可以用lambda编写一个函数并进行应用

代码语言:javascript
运行
复制
def len_consec_zeros(a):
    a = np.array(list(a))    # convert elements to `str`
    rr = np.argwhere(a == '0').ravel()  # find out positions of `0`
    if not rr.size:  # if there are no zeros, return 0
        return 0

    full = np.arange(rr[0], rr[-1]+1)  # get the range of spread of 0s

    # get the indices where `0` was flipped to something else
    diff = np.setdiff1d(full, rr)
    if not diff.size:     # if there are no bit flips, return the 
        return len(full)  # size of the full range

    # break the array into pieces wherever there's a bit flip
    # and the result is the size of the largest chunk
    pos, difs = full[0], []
    for el in diff:
        difs.append(el - pos)
        pos = el + 1

    difs.append(full[-1]+1 - pos)

    # return size of the largest chunk
    res = max(difs) if max(difs) != 1 else 0

    return res

既然你有了这个函数,就在每一行上调用它.

代码语言:javascript
运行
复制
# join all columns to get a string column

# assuming you have your data in `df`
df['concated'] = df.astype(str).apply(lambda x: ''.join(x), axis=1)
df['consecutive_zeros'] = df.concated.apply(lambda x: len_consec_zeros(x))
票数 1
EN

Stack Overflow用户

发布于 2017-07-24 14:08:49

对于每一行,您都希望cumsum(1-row)在每次row == 1时都进行重置。那你就占第一排。

例如

代码语言:javascript
运行
复制
ts = pd.Series([0,0,0,0,1,1,0,0,1,1,1,0])
ts2 = 1-ts
tsgroup = ts.cumsum()

consec_0 = ts2.groupby(tsgroup).transform(pd.Series.cumsum)
consec_0.max()

会视需要给你4个。

把它写在一个函数中并应用到您的dataframe中

票数 3
EN

Stack Overflow用户

发布于 2017-07-24 13:41:00

这里有一个方法-

代码语言:javascript
运行
复制
# Inspired by https://stackoverflow.com/a/44385183/
def pos_neg_counts(mask):
    idx = np.flatnonzero(mask[1:] != mask[:-1])
    if len(idx)==0: # To handle all 0s or all 1s cases
        if mask[0]:
            return np.array([mask.size]), np.array([0])
        else:
            return np.array([0]), np.array([mask.size])
    else:
        count = np.r_[ [idx[0]+1], idx[1:] - idx[:-1], [mask.size-1-idx[-1]] ]
        if mask[0]:
            return count[::2], count[1::2] # True, False counts
        else:
            return count[1::2], count[::2] # True, False counts

def get_consecutive_zeros(df):
    arr = df.values
    mask = (arr==0) | (arr=='0')
    zero_count = np.array([pos_neg_counts(i)[0].max() for i in mask])
    zero_count[zero_count<2] = 0
    return zero_count

样本运行-

代码语言:javascript
运行
复制
In [272]: df
Out[272]: 
  DEC JAN FEB  MARCH  APRIL  MAY
0   X   X   X      1      0    1
1   X   X   X      1      0    1
2   0   0   1      0      0    1
3   1   0   0      0      1    1
4   0   0   0      0      0    1
5   X   1   1      0      0    0
6   1   0   0      1      0    0
7   0   0   0      0      1    0

In [273]: df['consecutive_zeros'] = get_consecutive_zeros(df)

In [274]: df
Out[274]: 
  DEC JAN FEB  MARCH  APRIL  MAY  consecutive_zeros
0   X   X   X      1      0    1                  0
1   X   X   X      1      0    1                  0
2   0   0   1      0      0    1                  2
3   1   0   0      0      1    1                  3
4   0   0   0      0      0    1                  5
5   X   1   1      0      0    0                  3
6   1   0   0      1      0    0                  2
7   0   0   0      0      1    0                  4
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45281597

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档