数组上的 Numpy 迭代器没有按预期工作

Numpy iterator on array do not work as expected

我想声明一个对象数组,然后在其中包含数组。我可以这样做:

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

但是因为 Numpy 有迭代器,所以我想使用它们:

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

消息是:

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

谁能解释一下我的正确做法?

TIA

我不知道这是否正是您要查找的内容,但要使用 numpy 迭代器获得相同的结果,以下代码可能是您的答案。

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)

如果这不是您想要的,请根据您的要求更加具体

这是我喜欢的解决方案:

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 来自 github