[英]How to convert a python set to a numpy array?
I am using a set operation in python to perform a symmetric difference between two numpy arrays. 我在python中使用set操作来执行两个numpy数组之间的对称差异。 The result, however, is a set and I need to convert it back to a numpy array to move forward.
然而,结果是一个集合,我需要将它转换回一个numpy数组继续前进。 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)
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. 我可以循环遍历要逐个转换的元素,但我将拥有100,000个元素,并希望有一个内置函数来保存循环。 Thanks!
谢谢!
Do: 做:
>>> numpy.array(list(c))
array([1, 4, 6])
And dtype is int (int64 on my side.) 并且dtype是int(在我这边的int64。)
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会将各个元素设置为整数而不是第一个元素作为对象。
Try: 尝试:
numpy.fromiter(c, int, len(c))
This is twice as fast as the solution with list as a middle product. 这是使用list作为中间产品的解决方案的两倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.