Uylenburgh
Uylenburgh

Reputation: 1337

Modify actual element value in array numpy

I can't modify the actual value of a numpy array in a loop. My code is the following :

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

labels_class - is just a numpy array of size N and of values [0, 39]. The value of labels_class[label] is correct(==modified) in the loop, but outside of the loop labels_classremains unchanged.

I have also tried nditer, did not work :

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

In the reference, it is said that "to actually modify the element of the array, x should be indexed with the ellipsis"

How do I do that? What is the syntax?

Upvotes: 1

Views: 16608

Answers (3)

jliu1999
jliu1999

Reputation: 12

how about this?

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

Upvotes: 0

hpaulj
hpaulj

Reputation: 231665

The syntax for modifying array values with nditer is demonstrated at

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' refers to the x[...].

Indexing with enumerate is perfectly fine as well. But this is the way to do it with nditer. See later sections in the nditer page about using flags=['f_index'].

When iterating over arrays you need to clearly understand the difference between variables which are indexes, scalars, or array elements which can be modified. x = 1 is not the same as A[i]= 1 or x[...]=1.

Upvotes: 5

sedavidw
sedavidw

Reputation: 11741

Your iterator is not creating indices, but the actual elements in the array

for label in labels_class

In the above label is not an index, but the actual element you are trying to change

You can do something like this:

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

Upvotes: 7

Related Questions