I am going crazy trying to slice a 2D array according to values from another array:
# array of integer values:
aa = np.random.randint(500, 600, size=(5,5)
array([[574, 550, 548, 545, 551],
[547, 539, 539, 502, 528],
[503, 530, 582, 567, 505],
[590, 504, 510, 578, 525],
[530, 548, 501, 580, 583]])
# array of indices:
ab = np.random.randint(4, size=(5,5))
array([[3, 0, 2, 1, 1],
[3, 2, 2, 1, 3],
[0, 3, 1, 2, 0],
[1, 2, 3, 1, 3],
[3, 0, 1, 1, 0]])
What I want to return is a 2D subarray of aa, wherever ab is 1. But the closest I can get is:
aa[ab==1]
array([545, 551, 502, 582, 590, 578, 501, 580])
I'm always getting a 1D array as an output... How can I get my output array in the same dimensions as the original one?
EDIT: Sorry, I should have specified the expected output:
array([[545, 551],
[502],
[582],
[590, 578],
[501, 580]])
I also picked a poor example for the index array ab, it will always have the same number of 1s per row - so the output array would have the dimensions (5,2).
ab!=1do you just want to fill with0?numpy.where(ab == 1, aa, 0)numpy.ma.masked_array(data=aa, mask=(ab!=1), fill_value=0)(5,2), but(5,).