I am using a set operation in python to perform a symmetric difference between two numpy arrays. The result, however, is a set and I need to convert it back to a numpy array to move forward. Is there a way to do this? Here's what I tried:
我在python中使用set操作来执行两个numpy数组之间的对称差异。然而,结果是一个集合,我需要将它转换回一个numpy数组继续前进。有没有办法做到这一点?这是我尝试过的:
a = numpy.array([1,2,3,4,5,6])
b = numpy.array([2,3,5])
c = set(a) ^ set(b)
The results is a set:
结果是一组:
In [27]: c
Out[27]: set([1, 4, 6])
If I convert to a numpy array, it places the entire set in the first array element.
如果我转换为numpy数组,它会将整个集合放在第一个数组元素中。
In [28]: numpy.array(c)
Out[28]: array(set([1, 4, 6]), dtype=object)
What I need, however, would be this:
但是,我需要的是:
array([1,4,6],dtype=int)
I could loop over the elements to convert one by one, but I will have 100,000 elements and hoped for a built-in function to save the loop. Thanks!
我可以循环遍历元素以逐个转换,但我将拥有100,000个元素,并希望有一个内置函数来保存循环。谢谢!
3 个解决方案
#1
25
Don't convert the numpy array to a set to perform exclusive-or. Use setxor1d directly.
不要将numpy数组转换为set来执行exclusive-or。直接使用setxor1d。
>>> import numpy
>>> a = numpy.array([1,2,3,4,5,6])
>>> b = numpy.array([2,3,5])
>>> numpy.setxor1d(a, b)
array([1, 4, 6])
#2
27
Do:
做:
>>> numpy.array(list(c))
array([1, 4, 6])
And dtype is int (int64 on my side.)
并且dtype是int(我身边的int64。)
#3
6
Try this.
尝试这个。
numpy.array(list(c))
Converting to list before initializing numpy array would set the individual elements to integer rather than the first element as the object.
在初始化numpy数组之前转换为list会将各个元素设置为整数而不是第一个元素作为对象。
#1
25
Don't convert the numpy array to a set to perform exclusive-or. Use setxor1d directly.
不要将numpy数组转换为set来执行exclusive-or。直接使用setxor1d。
>>> import numpy
>>> a = numpy.array([1,2,3,4,5,6])
>>> b = numpy.array([2,3,5])
>>> numpy.setxor1d(a, b)
array([1, 4, 6])
#2
27
Do:
做:
>>> numpy.array(list(c))
array([1, 4, 6])
And dtype is int (int64 on my side.)
并且dtype是int(我身边的int64。)
#3
6
Try this.
尝试这个。
numpy.array(list(c))
Converting to list before initializing numpy array would set the individual elements to integer rather than the first element as the object.
在初始化numpy数组之前转换为list会将各个元素设置为整数而不是第一个元素作为对象。