python - 使用任何列表值过滤 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()
,但是是否有更通用的功能来实现这一点?
解决方案
您可以使用.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)
推荐阅读
- linux - 如何在卷曲字符串中使用公历时间戳
- java - 在时区的日期时间不明确的情况下抛出异常?
- angular - 为什么Angular Material源代码中的这一行有`|| 空`?
- xamarin - Xamarin.Forms:网格单元格可以包含多个标签吗?
- android - 如何禁用使用 Flutter 1.0 在 Google 地图中点击标记时出现的导航按钮?
- c# - 编译器错误消息:CS1513:} 预期如果是瀑布
- android - 当应用程序处于后台时,活动和片段会发生什么
- angular - 为什么我在写第一个字母时会失去输入的焦点?
- notepad++ - 如何删除notepd ++中的特定行
- php - Codeigniter:如何使模型代码可重用?