首页 > 解决方案 > 使用任何列表值过滤 pandas df

问题描述

我有一个熊猫数据框:

df
0       PL
1       PL
2       PL
3       IT
4       IT
        ..
4670    DE
4671    NO
4672    MT
4673    FI
4674    XX
Name: country_code, Length: 4675, dtype: object

我通过德国国家标签“DE”过滤这个:

df = df[df.apply(lambda x: 'DE' in x)]

如果我想过滤更多国家/地区而不是我必须通过手动添加它们:.apply(lambda x: 'DE' in x or 'GB' in x)。但是,我想创建一个国家列表并自动生成此语句。

像这样的东西:

countries = ['DE', 'GB', 'IT']
df = df[df.apply(lambda x: any_item_in_countries_list in x)]

我想我可以过滤 df 3 次,然后通过 合并这些片段concat(),但是是否有更通用的功能来实现这一点?

标签: pythonpandasfilterlambda

解决方案


您可以使用.isin()

df[df['country_code'].isin(['DE', 'GB', 'IT'])]

性能对比:

import timeit
import pandas as pd
df = pd.DataFrame({'country_code': ['DE', 'GB', 'IT', 'MT', 'FI', 'XX'] * 1000})

%timeit df[df['country_code'].isin(['DE', 'GB', 'IT'])]
409 µs ± 19 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df['country_code'].apply(lambda x: x in ['DE', 'AT', 'GB'])
1.35 ms ± 474 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

推荐阅读