Search code examples
pythonnumpyiterator

Numpy iterator on array do not work as expected


I want to declare an array of object and later to include arrays in it. I can do it this way:

import numpy as np    
v = np.empty([2,2], dtype=object)
for i in range(len(v.flat)):
  v.flat[i] = np.ones([3])

But since Numpy has iterators, I wanted to use them:

v = np.empty([2,2], dtype=object)
for i in np.nditer(v, flags=['refs_ok'],op_flags=['readwrite']):
  i[...] = np.ones([3])

and the message is:

ValueError: could not broadcast input array from shape (3) into shape()

Can someone explain my how to do it correctly?

TIA


Solution

  • And here is a solution I like:

    I am honestly not sure if this makes more sense or not (I would say it probably makes sense). But you can use i[()] = ... since you want to do item assignment not view based/sliced assignment anyway.

    Oh, and be careful with nditer and objects I forgot what the traps were, but I am pretty sure there are traps with the buffer and reference counts.

    seberg from github