熊猫:当组中的值落入范围内时,将组保留在数据中

时间:2018-07-26 23:39:18

标签: python pandas lambda filter

我在一个组中有值,如果该值在5到25的范围内,那么我想将此组保留在数据中。

基于Pandas: remove group from the data when a value in the group meets a required condition,我这样写:

dfnew = df.groupby('groupname').filter(lambda x: (x['column2']>=5) & (x['column2']<=25))

当我使用它时,出现此错误: filter function returned a Series, but expected a scalar bool

然后我也尝试过:

dfnew = df.groupby('groupname').filter(lambda x: 5<= x['column2']<=25)

但是它给出了错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

然后我尝试:

dfnew = df.groupby('groupname').filter(lambda x: (x['column2'].any()>=5) & (x['column2'].any()<=25))

仅返回具有列名称的空数据框

我对python和数据科学非常陌生(字面编码几天)。请说明发生了什么并提供帮助!非常感谢!!

1 个答案:

答案 0 :(得分:1)

我想你快到了。您需要使用maxmin来测试组中的值。这是一个带有玩具数据集的示例。

首先数据:

import pandas as pd

data = pd.DataFrame(
    {
        'id': [1, 2, 3] * 3,
        'value': [3, 20, 21, 6, 24, 7, 21, 8, 50]
    }
)

data

哪个给了我们

    id  value
0   1   3
1   2   20
2   3   21
3   1   6
4   2   24
5   3   7
6   1   21
7   2   8
8   3   50

然后使用组/过滤器模式仅保留组中的最小值大于或等于5且组中的最大值小于或等于25的组。在这种情况下,我们希望只返回第2组。

data.groupby('id').filter(lambda x: (x['value'].max() <= 25) & (x['value'].min() >= 5))

这就是我们得到的:

id  value
1   2   20
4   2   24
7   2   8
相关问题