【问题标题】:How to change the bool values in pd.Series if the count is more than some value in pandas如果计数大于熊猫中的某个值,如何更改 pd.Series 中的布尔值
【发布时间】:2019-04-08 09:21:21
【问题描述】:

我有以下布尔系列,我试图找到count,我必须检查False 值,如果连续系列中False 值的计数是greater than 2,那就让它false 但如果是count is less than equal to 2 then i have to inverse them,则来自False to True

预期的输出:就像第一次一样,False 重复两次,这意味着它将变为 True,但如果我们在 true 值之后看到 false 再次重复超过两次,因此这些值将保持为 false,

如何使用 Pandas 函数执行此操作?

True
True
True
True
True
False
False
True
True
True
True
True
True
True
False
False
False
False
False
False
True
True
True
True

【问题讨论】:

  • 您能否缩短示例(约 10 行就完美了)并提供预期的输出?
  • @coldspeed 输出正确解释请阅读信息

标签: python python-3.x pandas dataframe


【解决方案1】:

让我们尝试一些不同的东西

s=df.cumsum().mask(df)
df=df.mask(s.isin(s.value_counts()[s.value_counts()<=2].index),True)
df
0      True
1      True
2      True
3      True
4      True
5      True
6      True
7      True
8      True
9      True
10     True
11     True
12     True
13     True
14    False
15    False
16    False
17    False
18    False
19    False
20     True
21     True
22     True
23     True
Name: a, dtype: bool

【讨论】:

    【解决方案2】:

    尝试使用 groupbycumsum 生成唯一的 False 组,然后获取每个组的 count,如果该计数小于三个使用 ~ 反转该系列组并应用回系列mask:

    s.mask(s.groupby((s).cumsum().where(~s)).transform('count') < 3, ~s)
    

    输出:

    0      True
    1      True
    2      True
    3      True
    4      True
    5      True
    6      True
    7      True
    8      True
    9      True
    10     True
    11     True
    12     True
    13     True
    14    False
    15    False
    16    False
    17    False
    18    False
    19    False
    20     True
    21     True
    22     True
    23     True
    Name: 0, dtype: bool
    

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 1970-01-01
      • 2014-06-18
      • 2017-04-04
      • 2018-06-30
      • 2019-10-07
      • 1970-01-01
      • 2019-10-08
      相关资源
      最近更新 更多