5

I'm working with a dataset where non existent values show up as a negative number. I want to convert these values to np.nan values but I can't figure out how. The condition for this is (array < 0).

An example of what would happen to the array would be:

import numpy as np

array = np.array([[-1,  1, -1,  1],
                  [ 1, -1, -1,  1],
                  [ 1, -1, -1, -1]])

To then be converted to:

np.array([[np.nan,      1, np.nan,      1],
          [     1, np.nan, np.nan,      1],
          [     1, np.nan, np.nan, np.nan]])

Cheers

1 Answer 1

7

np.nan is a float so you need to convert array to float before doing the boolean masking.

isinstance(np.nan, float)  # True

array = array.astype(float)
array[array < 0] = np.nan
array

outputs

array([[nan,  1., nan,  1.],
       [ 1., nan, nan,  1.],
       [ 1., nan, nan, nan]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.