user3591466
user3591466

Reputation: 867

Is there a way to let numpy matrix to store object?

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

Upvotes: 3

Views: 1614

Answers (2)

Carsten
Carsten

Reputation: 18446

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')])

Upvotes: 1

mgilson
mgilson

Reputation: 309841

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)

Upvotes: 5

Related Questions