1

I'm not sure if I'm using the correct vocabulary here, but I have a use case for creating writable view into a numpy record array. I'm seeing a discrepancy in the way numpy behaves depending on how I do the selection. The following code snippet is a minimal example.

import numpy as np

a = np.asarray([(True, 1), (False, 2), (True, 3), (False, 4)], dtype=np.dtype([('b', 'b1'), ('i', 'i4')]))
mask = a['b']

a[mask]['i'] = 0
print((a[mask]['i'] == 0).all())  # this is false

a['i'][mask] = 0
print((a[mask]['i'] == 0).all())  # this is true

Is this intended behavior or is it a bug? Is there some other way go generate a sub-record array that avoids copying the data?

1 Answers1

0

Okay so here is the deal. When you use your mask first, it is creating a copy of your array, therefore when you try and change the values in a. a is not being changed, because the change only affects the copy.

You can read more about it here.

Nils
  • 910
  • 8
  • 30
  • I see. I guess I didn't realize the following two statements were different: `b = a[mask]; b[:] = 1` and `a[mask] = 1`. Makes sense now. – Jonathan Beezley Nov 11 '19 at 17:05