【问题标题】:Label contiguous groups of True elements within a pandas Series在 pandas Series 中标记连续的 True 元素组
【发布时间】:2019-03-26 18:47:39
【问题描述】:

我有一个熊猫系列的布尔值,我想标记连续的 True 值组。怎么可能做到这一点?是否有可能以矢量化的方式做到这一点?任何帮助将不胜感激!

数据:

     A  
0  False  
1  True  
2  True  
3  True  
4  False  
5  False  
6  True  
7  False  
8  False  
9  True  
10 True

期望:

     A    Label
0  False   0    
1  True    1   
2  True    1  
3  True    1  
4  False   0
5  False   0  
6  True    2
7  False   0
8  False   0
9  True    3
10 True    3

【问题讨论】:

    标签: python pandas time-series series


    【解决方案1】:

    这是一个不太可能但简单且有效的解决方案:

    import scipy.ndimage.measurements as mnts
    
    labeled, clusters = mnts.label(df.A.values)
    # labeled is what you want, cluster is the number of clusters.
    
    df.Labels = labeled # puts it into df
    

    测试为:

    a = array([False, False,  True,  True,  True, False,  True, False, False,
            True, False,  True,  True,  True,  True,  True,  True,  True,
            False, True], dtype=bool)
    
    labeled, clusters = mnts.label(a)
    
    >>> labeled
    array([0, 0, 1, 1, 1, 0, 2, 0, 0, 3, 0, 4, 4, 4, 4, 4, 4, 4, 0, 5], dtype=int32)
    
    >>> clusters
    5
    

    【讨论】:

    • 完美运行。非常感谢!
    【解决方案2】:

    cumsum

    a = df.A.values
    z = np.zeros(a.shape, int)
    
    z[a] = pd.factorize((~a).cumsum()[a])[0] + 1
    
    df.assign(Label=z)
    
            A  Label
    0   False      0
    1    True      1
    2    True      1
    3    True      1
    4   False      0
    5   False      0
    6    True      2
    7   False      0
    8   False      0
    9    True      3
    10   True      3
    

    【讨论】:

      【解决方案3】:

      您可以使用cumsumgroupby + ngroup 来标记群组。

      v = (~df.A).cumsum().where(df.A).bfill()   
      df['Label'] = (
          v.groupby(v).ngroup().add(1).where(df.A).fillna(0, downcast='infer'))
      
      df
             A  Label
      0   False      0
      1    True      1
      2    True      1
      3    True      1
      4   False      0
      5   False      0
      6    True      2
      7   False      0
      8   False      0
      9    True      3
      10   True      3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-24
        • 2020-04-15
        • 2019-01-02
        • 2023-03-07
        • 2019-01-04
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        相关资源
        最近更新 更多