I'm trying to execute the following
>> from numpy import *
>> x = array([[3,2,3],[4,4,4]])
>> y = set(x)
TypeError: unhashable type: 'numpy.ndarray'
How can I easily and efficiently create a set with all the elements from the Numpy array?
I'm trying to execute the following
>> from numpy import *
>> x = array([[3,2,3],[4,4,4]])
>> y = set(x)
TypeError: unhashable type: 'numpy.ndarray'
How can I easily and efficiently create a set with all the elements from the Numpy array?
If you want a set of the elements, here is another, probably faster way:
PS: after performing comparisons between
x.flat
,x.flatten()
, andx.ravel()
on a 10x100 array, I found out that they all perform at about the same speed. For a 3x3 array, the fastest version is the iterator version:which I would recommend because it is the less memory expensive version (it scales up well with the size of the array).
PS: There is also a NumPy function that does something similar:
This does produce a NumPy array with the same element as
set(x.flat)
, but as a NumPy array. This is very fast (almost 10 times faster), but if you need aset
, then doingset(numpy.unique(x))
is a bit slower than the other procedures (building a set comes with a large overhead).I liked xperroni's idea. But I think implementation can be simplified using direct inheritance from ndarray instead of wrapping it.
NumPy
ndarray
can be viewed as derived class and used as hashable object.view(ndarray)
can be used for back transformation, but it is not even needed in most cases.Adding to @Eric Lebigot and his great post.
The following did the trick for building a tensor lookup table:
output:
np.unique documentation
If you want a set of the elements:
For a set of the rows:
The above answers work if you want to create a set out of the elements contained in an
ndarray
, but if you want to create a set ofndarray
objects – or usendarray
objects as keys in a dictionary – then you'll have to provide a hashable wrapper for them. See the code below for a simple example:Using the wrapper class is simple enough:
The immutable counterpart to an array is the tuple, hence, try convert the array of arrays into an array of tuples: