【问题标题】:Assign group to consecutive 1s in a Pandas Column将组分配给 Pandas 列中的连续 1
【发布时间】:2020-04-02 23:23:19
【问题描述】:

我在 pandas 中有一个值为 0 和 1 的列。我想分配超过 9 个连续 1 的组号。

示例: 假设我的列值为:[1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1]

我想要一个新列或将同一列更改为:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,3,3,3,3,3,3,3,3,3,3,3]

我已经到了可以用另一个数字(例如 2)替换所有连续的 1(计数大于 9)的程度。这是代码:

def f(col, threshold=9):
    mask = col.groupby((col != col.shift()).cumsum()).transform('count').gt(threshold)
    mask &= col.eq(1)
    #print (mask)
    col.update(col.loc[mask].replace(1,2))
    return col

【问题讨论】:

  • 为什么人们会做这么长的例子?

标签: python pandas events time-series


【解决方案1】:

找到连续的 1 组并确定这些组的大小。使用where 屏蔽任何0 组或太小的1 组,然后ngroup 将允许您正确标记它们。 NaN 行被标记为 -1,并且您希望从 1 开始计数,因此添加 1 同时修复了这两个问题。

import pandas as pd
s = pd.Series([1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,
               1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,
               1,0,0,0,1,1,1,1,1,1,1,1,1,1,1])

u = s.ne(s.shift()).cumsum().where(s.eq(1))  # Label consecutive groups of 1s, NaN 0s
u = u.groupby(u).transform('size').gt(9)     # True only if 1s and size > 9.

# Any smaller groups or 0s get NaN'd by `where` which are labeled -1 by `ngroup`
result = u.groupby(u.ne(u.shift()).cumsum().where(u)).ngroup()+1

print(results.tolist())
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 
 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 
 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]

【讨论】:

    【解决方案2】:

    我的做法:

    s = pd.Series([1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,
                   1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,
                   1,0,0,0,1,1,1,1,1,1,1,1,1,1,1])
    
    # groupby and filter those with >=9 ones
    u = s.groupby(s.ne(1).cumsum()).transform('sum').ge(9) & s
    
    # count the groups of True:
    (~u.shift(fill_value=False) & u).cumsum().mul(u)
    

    输出:

    [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 2 2 2
     2 2 2 2 2 2 2 2 2 2 0 0 0 3 3 3 3 3 3 3 3 3 3 3]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2012-10-10
      • 2019-10-09
      • 2020-09-14
      相关资源
      最近更新 更多