I would like to store a tuple inside numpy matrix, but it seems like it will return an error. Is there a way to go about it?
>>> import numpy
>>> y = numpy.zeros((4,4))
>>> y[1][1] = (1,1)
ValueError: setting an array element with a sequence.
Thanks
use dtype=object and you can put anything in your array that you want:
>>> arr = np.zeros((4, 4), dtype=object)
>>> arr[1, 1] = (1, 1)
>>> arr
array([[0, 0, 0, 0],
[0, (1, 1), 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=object)
You can do this by using numpy's structured arrays. Example:
>>> import numpy as np
>>> y = np.zeros((4, 4), dtype=("i8, i8"))
array([[(0L, 0L), (0L, 0L), (0L, 0L), (0L, 0L)],
[(0L, 0L), (0L, 0L), (0L, 0L), (0L, 0L)],
[(0L, 0L), (0L, 0L), (0L, 0L), (0L, 0L)],
[(0L, 0L), (0L, 0L), (0L, 0L), (0L, 0L)]],
dtype=[('f0', '<i8'), ('f1', '<i8')])
>>> y[1,1] = (1,1)
>>> y
array([[(0L, 0L), (0L, 0L), (0L, 0L), (0L, 0L)],
[(0L, 0L), (1L, 1L), (0L, 0L), (0L, 0L)],
[(0L, 0L), (0L, 0L), (0L, 0L), (0L, 0L)],
[(0L, 0L), (0L, 0L), (0L, 0L), (0L, 0L)]],
dtype=[('f0', '<i8'), ('f1', '<i8')])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With