python - 使用 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”的行。
解决方案
Filtering with groupby
is 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')
推荐阅读
- javascript - 如何使用对主视图的移动做出反应的three.js和轨道控制添加覆盖部分?
- robotframework - Robot框架中的标签是什么
- node.js - 如何使用 axios 重试 5xx 请求
- java - 为什么我不能以这种方式关闭我的 JAR 可执行文件?
- powershell - 使用 powershell 获取证书信息
- php - 在两个小时的插槽中溢出数组
- c++ - 如何使用 C++ lambda 将成员函数指针转换为普通函数指针以用作回调
- ruby-on-rails - 一对一关系轨道中的 ActiveRecord::AssociationTypeMismatch
- java - 在 Java 中创建 keycloak 角色时出现错误 400 错误请求
- java - 通过比较日期和时间获取最后更新的用户