python - 检查一列是否与另一列的列表中的所有对象匹配
问题描述
我有一个带有一列字符串的数据框和另一个带有字符串列表的数据框。
0 1
0 apples are good [orange, banana]
1 bananas are good [bananas, bad]
2 cucumbers are green [cucumbers, are]
3 grapes are green [grapes, are, green]
4 oranges are good [oranges]
5 pineapples are big [flowers, apples]
我希望找到所有索引,其中的字符串Column 0
与Column 1
. 在这种情况下,输出将如下所示:
0 1
2 cucumbers are green [cucumbers, are]
3 grapes are green [grapes, are, green]
4 oranges are good [oranges]
我知道我可以使用pandas.Series.str.contains
,但这只适用于单个列表,我想尽可能避免迭代/循环。
解决方案
您可以使用列表推导和布尔索引:
res = df[[all(word in x.split() for word in y) for x, y in zip(df[0], df[1])]]
print(res)
0 1
2 cucumbers are green [cucumbers, are]
3 grapes are green [grapes, are, green]
4 oranges are good [oranges]
推荐阅读
- git - 在执行 `git checkout master --patch` 后解决 `git merge master` 冲突
- hadoop - 无法在加载数据的 Hive 表中插入数据
- javascript - 正则表达式正在接受带有符号的单词
- http - 无法通过 https 卷曲在 aws ec2 上运行的应用程序,但 http 有效
- javascript - 我如何让一堆正方形看起来像克罗地亚的边界?
- django - 按地理空间数据排序并根据字段向上移动特定记录 - ElasticSearch DSL DRF
- excel - 尝试插入或删除列
- c - 从 Visual Studio 编译程序集输出时符号已定义错误
- c++ - 带有 const ref 参数的函数模板特化
- r - 如何在 r 中编写一个函数来绘制每个唯一值的数据?