'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 1:[1]

I don't know if it is exactly what you are looking, but to have the same result using numpy iterator, the following code maybe could be your answer.

v = np.empty([2,2], dtype=object)

for idRow,idCol in np.ndindex(np.shape(v)):
    v[idRow,idCol] = np.ones(3)
    print(idRow, idCol)

If it's not what you are looking, be more specfici on your request

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guillaume Jacquenot