Python - 比较两列特征,返回两者不共同的值 [英] Python - Compare two columns of features, return values which are not common to both

查看:74
本文介绍了Python - 比较两列特征,返回两者不共同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较两列特征(a",b")并仅返回两者不共同的值.行大小不等,值可能出现多次.

I would like to compare two columns of features("a", "b") and return only values which are not common to both. The rows are of unequal size, and values may occur more than once.

我试过了:

a[np.logical_not(np.in1d(a,b))]

但是如果 len(b) > len(a)

But this doesn't seem to work if len(b) > len(a)

有什么建议吗?

推荐答案

IIUC 您正在寻找 Symmetric区别:

IIUC you are looking for a Symmetric difference:

源 DF:

In [41]: d1
Out[41]:
   a
0  a
1  b
2  c
3  x
4  d
5  l
6  z

In [42]: d2
Out[42]:
   b
0  b
1  a
2  d
3  c
4  y

Numpy 解决方案:

In [43]: np.setdiff1d(np.union1d(d1.a, d2.b), np.intersect1d(d1.a, d2.b))
Out[43]: array(['l', 'x', 'y', 'z'], dtype=object)

熊猫解决方案:

In [44]: pd.Index.symmetric_difference(pd.Index(d1.a), pd.Index(d2.b))
Out[44]: Index(['l', 'x', 'y', 'z'], dtype='object')

这篇关于Python - 比较两列特征,返回两者不共同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆