【问题标题】:Pandas - changing rows where less than n subsequent values are equalPandas - 更改小于 n 个后续值相等的行
【发布时间】:2021-11-15 14:51:09
【问题描述】:

我有以下数据框:

df = pd.DataFrame({"col":[0,0,1,1,1,1,0,0,1,1,0,0,1,1,1,0,1,1,1,1,0,0,0]})

现在我想将所有行设置为零,其中少于四个 1 出现“连续”,即我希望得到以下结果 DataFrame:

df = pd.DataFrame({"col":[0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0]})

我无法找到一种很好地实现这一目标的方法......

【问题讨论】:

  • 有几个类似的问题。要识别1 块,请使用df['col'].ne(1).cumsum()。然后按这些块分组并变换大小。

标签: python pandas dataframe row equals


【解决方案1】:

试试groupbywhere

streaks = df.groupby(df["col"].ne(df["col"].shift()).cumsum()).transform("sum")
output = df.where(streaks.ge(4), 0)

>>> output
    col
0     0
1     0
2     1
3     1
4     1
5     1
6     0
7     0
8     0
9     0
10    0
11    0
12    0
13    0
14    0
15    0
16    1
17    1
18    1
19    1
20    0
21    0
22    0

【讨论】:

    【解决方案2】:

    我们可以的

    df.loc[df.groupby(df.col.eq(0).cumsum()).transform('count')['col']<5,'col'] = 0
    df
    Out[77]: 
        col
    0     0
    1     0
    2     1
    3     1
    4     1
    5     1
    6     0
    7     0
    8     0
    9     0
    10    0
    11    0
    12    0
    13    0
    14    0
    15    0
    16    1
    17    1
    18    1
    19    1
    20    0
    21    0
    22    0
    

    【讨论】:

      猜你喜欢
      • 2022-11-19
      • 1970-01-01
      • 2016-01-21
      • 2018-12-04
      • 2022-10-14
      • 2015-02-18
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多