首页 > 解决方案 > 过滤条件 pandas df 包含一个列表

问题描述

我有一个 df,它的单元格内有列表对象:

data['country_code']
0       [IT, IT]
1       [PL, PL]
2       [IT, IT]
3       [IT, IT]
4       [IT, IT]
          ...   
6318    [XX, MT]
6319    [FI, FI]
6320    [XX, XX]
6321    [FI, FI]
6322    [FI, FI]
Name: country_code, Length: 6323, dtype: object

data如果列表中data['country_code']'SK''CZ' 作为第一个或第二个元素,我想过滤数据框

像这样的东西:

data[first element of data['country_code'] == 'SK'or'CZ' or second element of data['country_code'] == 'SK'or'CZ']

在 MongoDB 语法中,它将是:

.find({$or: [{country_code: $elemMatch = 'SK'}, {country_code: $elemMatch = 'CZ'}]})

标签: pythonpandaslistfilterconditional-statements

解决方案


您可以使用:

print(df[df.country_code.apply(lambda x: "SK" in x or "CZ" in x)])

印刷:

  country_code
3     [IT, CZ]
4     [SK, IT]

df用过的:

  country_code
0     [IT, IT]
1     [PL, PL]
2     [IT, IT]
3     [IT, CZ]
4     [SK, IT]

推荐阅读