合并两个Numpy数组并删除重复项? [英] Merge two numpy arrays and delete duplicates?
问题描述
我有一个numpy数组=
I have one numpy array =
[1,6,7,9,3,5]
和第二个numpy数组=
and a second numpy array =
[3,5,8,9,2]
我想合并这两个数组在一起:
I would like to merge these two arrays together:
[1,6,7,9,3,5,3,5,8,9,2]
,然后删除numpy数组中的重复项以获得:
and then remove the duplicates in the numpy array to get :
[1,6,7,9,3,5,8,2]
我想保留尽可能多的数组1并取出数组2中没有出现在数组1中的元素,然后追加这些元素。
I would like to keep as much of array one as possible and take out elements of array two, that don't appear in array one, and append these.
我不确定是否更有意义:
I am not sure if it makes more sense to:
- 合并两个数组并删除重复项。
或 - 循环遍历数组2的元素,如果它们未出现在数组1中,则连接到数组1。
我尝试使用各种循环,但这些循环似乎主要用于列表,我也尝试使用 set()
,但这订购 numpy
数组,我想保留随机订购单。
I have tried using various loops but these appear to work mostly for lists, I have also tried using set()
but this orders the numpy
array, I would like to keep the random order form.
推荐答案
要加入两个数组,只需使用 np.concatenate
To join the two arrays, you can simply use np.concatenate
在保留订单的同时删除重复项有些棘手,因为通常 np.unique
也可以排序,但是您可以使用 return_index
然后进行排序以解决此问题:
Removing duplicates while preserving order is a bit tricky, because normally np.unique
also sorts, but you can use return_index
then sort to get around this:
In [61]: x
Out[61]: array([1, 6, 7, 9, 3, 5])
In [62]: y
Out[62]: array([3, 5, 8, 9, 2])
In [63]: z = np.concatenate((x, y))
In [64]: z
Out[64]: array([1, 6, 7, 9, 3, 5, 3, 5, 8, 9, 2])
In [65]: _, i = np.unique(z, return_index=True)
In [66]: z[np.sort(i)]
Out[66]: array([1, 6, 7, 9, 3, 5, 8, 2])
这篇关于合并两个Numpy数组并删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!