I have a pandas dataframe:
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 并通过
concat()
将这些块合并,但是否有更通用的函数来实现这一点?
.apply(lambda x: x in ['DE', 'AT', 'GB'])
,此外您想进行基准测试吗? - oakca