【问题标题】:How to get rows when specific column value is continous for certain number of rows当特定列值对于特定行数连续时如何获取行
【发布时间】:2021-05-04 16:51:12
【问题描述】:

当列 x 值连续超过 5 行保持不变时,我想提取行。

     x  x2
0    5   5
1    4   5
2   10   6
3   10   5
4   10   6
5   10  78
6   10  89
7   10  78
8   10  98
9   10   8
10  10  56
11  60  45
12  10  65

Desired_output:

    x  x2
0  10   6
1  10   5
2  10   6
3  10  78
4  10  89
5  10  78
6  10  98
7  10   8
8  10  56

【问题讨论】:

    标签: python-3.x pandas numpy pandas-groupby


    【解决方案1】:

    您可以使用shift 比较下一行,如果重复大于 5,则使用累积和进行比较,然后对x 进行分组并转换any,然后使用条件屏蔽以取消选择条件所在的行不匹配。

    c = df['x'].eq(df['x'].shift())
    out = df[c.cumsum().gt(5).groupby(df['x']).transform('any') & (c|c.shift(-1))]
    

    print(out)
    
         x  x2
    2   10   6
    3   10   5
    4   10   6
    5   10  78
    6   10  89
    7   10  78
    8   10  98
    9   10   8
    10  10  56
    

    【讨论】:

      【解决方案2】:

      您可以使用 .shift + .cumsum 来识别列x 值保持不变的连续行块,然后将数据帧分组到这些块上和transform 使用count 来识别在x 中具有大于5 连续相同值的组:

      b = df['x'].ne(df['x'].shift()).cumsum()
      df_out = df[df['x'].groupby(b).transform('count').gt(5)]
      

      详情:

      >>> b
      0     1
      1     2
      2     3
      3     3
      4     3
      5     3
      6     3
      7     3
      8     3
      9     3
      10    3
      11    4
      12    5
      Name: x, dtype: int64
      
      >>> df_out
           x  x2
      2   10   6
      3   10   5
      4   10   6
      5   10  78
      6   10  89
      7   10  78
      8   10  98
      9   10   8
      10  10  56
      

      【讨论】:

      • 我只想在 x 的值为 10 时获得连续的行,如果其他值有连续的行我不需要
      • 在这种情况下你可以使用df[df['x'].groupby(b).transform('count').gt(5) & df['x'].eq(10)]
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 2012-09-05
      • 1970-01-01
      相关资源
      最近更新 更多