修改数组numpy中的实际元素值

Modify actual element value in array numpy

我无法在循环中修改 numpy 数组的实际值。 我的代码如下:

labels_class = np.copy(labels_train)
for label in labels_class:
  labels_class[label] = 1 if (label == classifier) else 0

labels_class - 只是一个大小为 N 且值为 [0, 39] 的 numpy 数组。 labels_class[label]的值在循环内是正确的(==修改),但在循环外labels_class保持不变。

我也试过nditer,没用:

 for label in np.nditer(labels_class, op_flags=['readwrite']):
      label = 1 if (label == classifier) else 0

reference中表示"to actually modify the element of the array, x should be indexed with the ellipsis"

我该怎么做?语法是什么?

您的迭代器不是在创建索引,而是在数组中创建实际元素

for label in labels_class

上面的 label 不是索引,而是您要更改的实际元素

你可以这样做:

for i, label in enumerate(labels_class):
     labels_class[i] = 1 if (label == classifier) else 0

使用 nditer 修改数组值的语法在

处进行了演示

http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#modifying-array-values

a = np.arange(6).reshape(2,3)
for x in np.nditer(a, op_flags=['readwrite']):
    x[...] = 2 * x

'x should be indexed with the ellipsis'指的是x[...].

使用 enumerate 建立索引也非常好。但这是 nditer 的处理方式。请参阅 nditer 页面中有关使用 flags=['f_index'].

的后续部分

在遍历数组时,您需要清楚地了解变量之间的区别,这些变量是索引、标量或可修改的数组元素。 x = 1A[i]= 1x[...]=1 不同。

这个怎么样?

labels_class[label_class == classifier] = 1
labels_class[label_class != classifier] = 0