python - 过滤条件 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'}]})
解决方案
您可以使用:
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]
推荐阅读
- javascript - 如何在 Promise 函数中抛出不同的错误?
- keras - 使用 Keras 和 TF2.0 的 Eager vs 图形模式
- html - 如何启用按音节自动断字?
- speech-recognition - 如何在 Mozilla DeepSpeech 中将成绩单保存到文本文件中?
- node.js - 使用 set 仅更新 Firestore 事务中的一部分写入属性
- android - 在 ViewPager2 android 中检测过度滚动或页面结束事件
- azure - Azure ARM 模板部署:授权问题
- c# - 将整数转换为罗马数字的控制器方法
- javascript - jquery序列化收集按名称分组值的倍数形式
- docker - 带有 redis 的 Celery:实例状态已更改(主 -> 副本?)