3

I have two multi-dimensional numpy array. I would like to convert the entry in the second array to NaN, if the corresponding element in first is zero. Below is example to manually mimic the same: (Can this be done programmatically)

import numpy as np    
a = np.random.rand(4,5)
a[0][0] = 0
a[1][0] = 0
a[1][1] = 0

b = np.random.rand(4,5)
b[0][0] = np.nan
b[1][0] = np.nan
b[1][1] = np.nan

Can we use masking here?

3
  • 1
    Loop over the first array, assign elements of the 2nd array based on the elements you are iterating over. for i in range(len(a)): for j in range(len(a[i])): if (a[i][j] == 0) b[i][j] = np.nan Commented May 18, 2020 at 6:52
  • Thank Vince! I would like to avoid looping though! Commented May 18, 2020 at 6:57
  • 2
    @VinceEmigh That's bad advice for numpy arrays. If you must use loops consider lists instead. Numpy shines with vector operations, but fails (performance wise, and badly) with iterative algorithms. Commented May 18, 2020 at 7:00

1 Answer 1

3

Write it like you say it:

b[a==0] = np.nan
Sign up to request clarification or add additional context in comments.

3 Comments

Very nice, didn't know you could inline the condition like that in Python 👌
@VinceEmigh Yup, numpy indexing is awesome. The manual on it is quite extensive.
@VinceEmigh It's very powerful, check numpy.org/devdocs/user/basics.indexing.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.