The Python Oracle

Cleanest way to replace np.array value with np.nan by user defined index

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC B Schuberts Piano Sonata No 16 D

--

Chapters
00:00 Question
01:31 Accepted answer (Score 4)
02:20 Answer 2 (Score 2)
03:02 Thank you

--

Full question
https://stackoverflow.com/questions/3626...

Answer 1 links:
[np.logical_and]: http://docs.scipy.org/doc/numpy-1.10.0/r...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #arrays

#avk47



ACCEPTED ANSWER

Score 4


You are nearly there.

You can pass arrays of indices to arrays. You probably know this with 1D-arrays.

With a 2D-array you need to pass the array a tuple of lists (one tuple for each axis; one element in the lists (which have to be of equal length) for each array-element you want to chose). You have a list of tuples. So you have just to "transpose" it.

t1 = zip(*t)

gives you the right shape of your index array; which you can now use as index for any assignment, for example: value[t1] = np.NaN

(There are lots of nice explanation of this trick (with zip and *) in python tutorials, if you don't know it yet.)




ANSWER 2

Score 2


You can use np.logical_and

arr = np.zeros((20,20))

You can select by location, this is just an example location.

arr[4:8,4:8] = 1

You can create a mask the same shape as arr

mask = np.ones((20,20)).astype(bool)

Then you can use the np.logical_and.

mask = np.logical_and(mask, arr == 1)

And finally, you can replace the 1s with the np.nan

arr[mask] = np.nan