如何将python集转换为numpy数组?
我正在python中使用set操作在两个numpy数组之间执行对称差异.但是,结果是一个集合,我需要将其转换回numpy数组以继续前进.有没有办法做到这一点?这是我尝试过的:
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:
a = numpy.array([1,2,3,4,5,6])
b = numpy.array([2,3,5])
c = set(a) ^ set(b)
结果是一组:
In [27]: c
Out[27]: set([1, 4, 6])
如果我转换为numpy数组,它将整个集合放在第一个数组元素中.
If I convert to a numpy array, it places the entire set in the first array element.
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)
我可以遍历元素以一次一转换,但是我将有100,000个元素,并希望有一个内置函数来保存循环.谢谢!
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!
不要将numpy数组转换为执行异或的数组.
Don't convert the numpy array to a set to perform exclusive-or. Use setxor1d directly.
>>> 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])