python - 如何查找 Pandas Column 中存在的任何共同点
问题描述
我有一个如下所示的 DataFrame:
IDS Metric
1,2 100
1,3 200
3 300
...
我想查找任意两个ID存在于同一行,例如“1,2”和“1,3”都存在于一行,但“2,3”没有直接关系(意味着它们之间没有竞争商业)
我想要一个函数来判断任何两个共同存在的 ID 并返回 True/False。
仅对于“判断任何两个共同存在的 ID”,我认为以下方法可能有效:
target_list = ['1', '2']
df["IDS"].apply(lambda ids: all(id in ids for id in target_list)).any()
# return True
target_list = ['2', '3']
df["IDS"].apply(lambda ids: all(id in ids for id in target_list)).any()
# return False
但是,由于lambda函数会迭代df中的每一行,迭代所有行可能效率低下,因为我只需要判断是否存在。我希望它应该在第一次共同存在发生时返回。
有人可以帮我吗?非常感谢
解决方案
利用:
df["IDS"].str.split(',', expand=True).isin(target_list).all(axis=1).any()
集合的另一个想法:
target_list = ['1', '2']
s = set(target_list)
a = any(s.issubset(x.split(',')) for x in df["IDS"])
print (a)
True
详情:
print (df["IDS"].str.split(',', expand=True))
0 1
0 1 2
1 1 3
2 3 None
print (df["IDS"].str.split(',', expand=True).isin(target_list))
0 1
0 True True
1 True False
2 False False
print (df["IDS"].str.split(',', expand=True).isin(target_list).all(axis=1))
0 True
1 False
2 False
dtype: bool
print (df["IDS"].str.split(',', expand=True).isin(target_list).all(axis=1).any())
True
推荐阅读
- python - Python 打印嵌套列表的内存地址而不是列表内容
- google-maps - Google Roads API 的 Nearest Roads 函数返回的点数多于给定点,包含重复项
- java - 如何在分页中获得总结果数
- javascript - 在 React 组件中存储多个引用与通过 ID 查询 DOM
- c# - 如果分隔符是一个或多个空格,如何拆分字符串?
- sql - SQL Select 在具有 25M 记录的表上花费太多时间
- typo3 - Typo3 将 7.6.31 升级到 8.7.19 / 数据库分析器失败
- python - 将 tf.Keras 与 TensorFlow 优化器一起使用
- python - 获取依赖文件以在 Binder 上托管 Jupyter 笔记本?
- vue.js - 路线无效(Vue.js)