首页 > 解决方案 > 如何查找 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中的每一行,迭代所有行可能效率低下,因为我只需要判断是否存在。我希望它应该在第一次共同存在发生时返回。

有人可以帮我吗?非常感谢

标签: pythonpandasdataframe

解决方案


利用:

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

推荐阅读