<分区>
我正在尝试理解 .filter() Pandas 中的方法。我不确定为什么下面的代码不起作用:
# 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
我很欣赏有更简单的方法来做到这一点(例如 bool 索引),但出于学习目的,我试图理解为什么 filter
在适用于 groupby
时会在这里失败> 如下图:
这个有效:
filtered_df = df.groupby('petal width (cm)').filter(lambda x: x['sepal width (cm)'].sum() > 50)