【问题标题】:Python Pandas groupby: filter according to condition on valuesPython Pandas groupby:根据值的条件过滤
【发布时间】:2023-04-02 09:34:02
【问题描述】:

考虑如下的数据框。

import pandas as pd

# Initialize dataframe
df1 = pd.DataFrame(columns=['bar', 'foo'])
df1['bar'] = ['001', '001', '001', '001', '002', '002', '003', '003', '003']
df1['foo'] = [-1, 0, 2, 3, -8, 1, 0, 1, 2]
>>> print df1
   bar  foo
0  001   -1
1  001    0
2  001    2
3  001    3
4  002   -8
5  002    1
6  003    0
7  003    1
8  003    2

# Lower and upper bound for desired range
lower_bound = -5
upper_bound = 5

我想在 Pandas 中使用 groupby 来返回一个数据框,该数据框过滤掉符合条件的 bar 行。特别是,如果此 barfoo 值之一不在 lower_boundupper_bound 之间,我想过滤掉带有 bar 的行。

在上面的例子中,bar = 002 的行应该被过滤掉,因为不是所有bar = 002 的行在-55 之间都包含foo 的值(即行索引4包含foo = -8)。此示例所需的输出如下。

# Desired output
   bar  foo
0  001   -1
1  001    0
2  001    2
3  001    3
6  003    0
7  003    1
8  003    2

我尝试了以下方法。

# Attempted solution
grouped = df1.groupby('bar')['foo']
grouped.filter(lambda x: x < lower_bound or x > upper_bound)

但是,这会产生 TypeError: the filter must return a boolean result。此外,当我希望结果返回一个数据框对象时,这种方法可能会返回一个 groupby 对象。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您很可能不会使用andor,而是将&amp;|pandas 一起使用,对于您的情况,然后在过滤器中应用all() 函数来构造布尔条件,这使bar 保持所有对应的foo 值在lower_boundupper_bound 之间:

    df1.groupby('bar').filter(lambda x: ((x.foo >= lower_bound) & (x.foo <= upper_bound)).all())
    
    #   bar foo
    #0  001 -1
    #1  001  0
    #2  001  2
    #3  001  3
    #6  003  0
    #7  003  1
    #8  003  2
    

    【讨论】:

    • 这对我不起作用。我仍然收到过滤器必须返回布尔结果的错误
    【解决方案2】:

    Psidom 的答案工作正常,但在大型数据集上可能会很慢。 我的在某种程度上是一种解决方法,但速度很快。

    df1['conditions_apply'] = (df1.foo >= lower_bound) & (df1.foo <= upper_bound)
    selection = df1.groupby('bar')['conditions_apply'].min()  # any False will return False
    selection = selection[selection].index.tolist()           # get all bars with Trues
    df1 = df1[df1.bar.isin(selection)]                        # make selection
    df1.drop(columns=['conditions_apply'], inplace=True)      # drop newly made column
    

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 2018-07-22
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多