【发布时间】:2018-06-26 13:19:23
【问题描述】:
我正在尝试理解 Pandas 中的 .filter() 方法。我不确定为什么下面的代码不起作用:
# Load data
from sklearn.datasets import load_iris
import pandas as pd
data = load_iris()
df = pd.DataFrame(data.data, columns=data.feature_names)
# Set arbitrary index (is this needed?) and try filtering:
indexed_df = df.copy().set_index('sepal width (cm)')
test = indexed_df.filter(lambda x: x['petal length (cm)'] > 1.4)
我明白了:
TypeError: 'function' object is not iterable
我很欣赏有更简单的方法可以做到这一点(例如布尔索引),但我试图理解为什么 filter 在适用于 groupby 时会在此处失败,如下所示:
这行得通:
filtered_df = df.groupby('petal width (cm)').filter(lambda x: x['sepal width (cm)'].sum() > 50)
【问题讨论】:
-
链接到的文档有四个参数:
items、like、regex和axis。 (如果您阅读文档)都不接受函数/lambda 表达式。 -
filter用于根据列名的部分匹配和正则表达式匹配来选择列。 -
你应该只使用普通的布尔索引。
-
谢谢威廉(和其他人)。我可以很高兴地通过布尔索引来做——我问的唯一原因是它是 DataCamp 课程的一个例子,尽管使用了
groupby,然后是filter和lambda函数。这部分对我来说仍然不清楚,因为它与groupby一起使用 - 我将编辑问题以使其明确。 -
要清楚,这不是布尔索引问题的完全重复,它是关于为什么
filter与groupby一起工作而不是没有。