试图找出一个 pandas df 是否是另一个 pandas df 的子集
当索引匹配时,我可以比较两个数据帧,但在我的例子中,行具有不同的索引
ex = pd.DataFrame({"col1": ["banana", "tomato", "apple"],
"col2": ["cat", "dog", "kangoo"],
"col3": ["tv", "phone", "ps4"]})
ex2 = pd.DataFrame({"col1": [ "tomato", "apple"],
"col2": [ "dog", "kangoo"],
"col3": [ "phone", "ps4"]})
ex2.isin(ex).all().all()
>>> False
我希望上面的结果匹配并显示为 True,目前它只查找相同的索引,我该如何覆盖它。
最佳答案
可能的解决方案是对所有列使用merge
(无参数on
),然后对子集使用isin
:
print (ex2.merge(ex).isin(ex2))
col1 col2 col3
0 True True True
1 True True True
print (ex2.merge(ex).isin(ex2).all().all())
True
另一个想法是比较 MultiIndex
es:
i1 = ex2.set_index(ex2.columns.tolist()).index
i2 = ex.set_index(ex.columns.tolist()).index
print (i1.isin(i2).all())
True
关于python - 查找数据框是否是另一个数据框的子集,同时忽略索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57144813/