I struggle with a error like below. I saw this code from another book, but it doesn't work. How can I solve it? Thanks in advance!
import numpy as np
a = [1, 2, 3, 2]
Ma = np.mat(a)
Sa2 = set(Ma) #error
I struggle with a error like below. I saw this code from another book, but it doesn't work. How can I solve it? Thanks in advance!
import numpy as np
a = [1, 2, 3, 2]
Ma = np.mat(a)
Sa2 = set(Ma) #error
You can use the following in order to flatten the matrix to an ndarray.
import numpy as np
a = [1, 2, 3, 2]
Ma = np.mat(a)
Sa2 = set(np.asarray(Ma).ravel())
print (Sa2)
>>> '{1, 2, 3}'
You can use Ma.A1
to convert the matrix to a 1d array, which displays as a simple list. Wrap that in tuple makes an object that is hashable.
>>> import numpy as np
>>> a = [1, 2, 3, 2]
>>> Ma = np.mat(a)
>>> Sa2 = set(Ma)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'matrix'
>>> set(Ma.A1)
set([1, 2, 3])
Another way:
>>> set(Ma.flat)
set([1, 2, 3])
See more details from Set of matrices
set
tries to iterate on its input, in effect treating it as a list:
In [61]: list(np.mat([1,2,3,4]))
Out[61]: [matrix([[1, 2, 3, 4]])] # a 1 item list
In [62]: list(np.mat([1,2,3,4]).A1)
Out[62]: [1, 2, 3, 4]
np.mat
turns its input into a (1,4) array, and any iteration on that produces the same thing. And set
can't hash the whole matrix object.
What do you want a set
of, the 4 numbers in the matrix? Or a 'row' of the matrix? set
does not work with nested lists or lists containing arrays or matrices. The elements of the set have to be 'hashable', immutable. Numbers and tuples work. Lists and dictionaries don't.