Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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) 

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.

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!

like image 254
mishaF Avatar asked Dec 11 '11 17:12

mishaF


People also ask

How do I turn an array into a NumPy array?

Convert a list to a NumPy array: numpy. You can convert a list to a NumPy array by passing a list to numpy. array() . The data type dtype of generated numpy. ndarray is automatically determined from the original list but can also be specified with the dtype parameter.

Does NumPy have set?

NumPy Set OperationsSets are used for operations involving frequent intersection, union and difference operations.

How do I turn a list into an array?

Create a List object. Add elements to it. Create an empty array with size of the created ArrayList. Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it.


2 Answers

Do:

>>> numpy.array(list(c)) array([1, 4, 6]) 

And dtype is int (int64 on my side.)

like image 144
tito Avatar answered Oct 08 '22 16:10

tito


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]) 
like image 22
kennytm Avatar answered Oct 08 '22 17:10

kennytm