0

So I have an array I am trying to slice and index using two other boolean arrays and then set a value on that subset of the array. I saw this post: Setting values in a numpy arrays indexed by a slice and two boolean arrays

and suspect I am getting a copy instead of a view of my array so it isn't saving the values I am setting on the array. I think I managed to reproduce the problem with a much shorter code, but am a very out of my depth.

#first array
a = np.arange(0,100).reshape(10,10)

#conditional array of same size
b = np.random.rand(10,10)
b = b < 0.8

#create out array of same size as a
out = np.zeros(a.shape)

#define neighborhood to slice values from
nhood = tuple([slice(3,6),slice(5,7)])

#define subset where b == True in neighborhood
subset = b[nhood]

#define values in out that are in the neighborhood but not excluded by b
candidates = out[nhood][subset]

#get third values from neighborhood using math
c = np.random.rand(len(candidates))
#this is in a for loop so this is checking to see a value has already been changed earlier - returns all true now
update_these = candidates < c
#set sliced, indexed subset of array with the values from c that are appropriate
out[nhood][subset][update_these] = c[update_these]

print(out) ##PRODUCES - ARRAY OF ALL ZEROS STILL

I have also tried chaining the boolean index with

out[nhood][(subset)&(update_these)] = c[update_these]

But that made an array of the wrong size.

Help?

ZachK
  • 21
  • 5
  • 1
    Look at `out[nhood][subset]`. `nhood` is a slice, and produces a `view`, but `[subset]` is boolean indexing, and produces a 1d copy. `out[nhood][subset]=...` can set those values. But you can't use the added `[update_these]` layer of indexing. – hpaulj Oct 25 '20 at 04:33
  • `c` is one-dimensional array, `update_this` is a 10-by-10 boolean mask. Therefore, `c[update_this]` is not compatible. You can reshape `c` or write a loop to determine which entries to consider. – Kate Melnykova Oct 25 '20 at 04:44
  • So if I use the out[nhood][subset] I can set values, but I want to only set values to the array if they are lower than the already existing values. Do I need to add a second set of indexing to do that check? Or should I combine the update_these and subset masks in an earlier step? – ZachK Oct 25 '20 at 05:12
  • Thanks for the replies. I might have gotten it working based on that answer @hpaulj . 'a_1 = out[nhood][subset] a_1[update_these] = c[update_these] out[nhood][subset] = a_1` I edited the last part of the code to extract the copy from `out[nhood][subset]` and then use boolean indexing to change that copy and that edit the original out dataframe. I suspect there is a smoother way to do that, but it seems to be working? – ZachK Oct 25 '20 at 05:29

0 Answers0