首页 > 解决方案 > 使用 lambda 创建过滤器会产生 bool 错误

问题描述

我想从列 payment_type 中过滤掉值“UNK”并返回完整的数据框。我想使用匿名函数。我收到类型错误。

我尝试创建一个单独的函数,但仍然无法使其工作。我在 Jupyter Notebooks 上运行它

paymentGroups = fareData.groupby("payment_type")

filteredPaymentTypes = paymentGroups.filter(lambda x: 
                                   x["payment_type"].values != 'UNK')

我收到此错误:

TypeError: filter function returned a ndarray, but expected a scalar bool

所需的结果是修改后的数据框,其中没有在 payment_type 列中包含“UNK”的行。

标签: pythonpandasfilter

解决方案


Filtering with groupbyis needed when the selection condition relates to some property of the whole group , eg the mean value of some column (within the current group) > some_value .

但是在您的情况下,选择标准与当前记录中的单个列 (不在组中)有关,因此不需要分组。改为使用query,例如:

fareData.query("payment_type != 'UNK'")

编辑

如果由于某种原因您仍想使用分组,请注意在这种情况下过滤是在分组键 ( payment_type) 上,这 在当前组的每一行中都是相同的。

所以过滤条件只能在 当前组的第一行检查感兴趣的值:

paymentGroups.filter(lambda x: x['payment_type'].iloc[0] != 'UNK')

推荐阅读