0

I'd like to read a 1D numpy array in Python and generate two other numpy arrays:

  • first one is the input, if there is no 'nan' values. Otherwise, input with 'nan' values replaced by '0'
  • second one is a mask, 1='input value is not 'nan'', and '0'='input value is nan''

For example:

a = numpy.array([1,2,numpy.nan,4])

would give

[1,2,0,4]
[1,1,0,1]

What's the most efficient way to do this in python ?

Thanks

2
  • Have a look at numpy.ma.masked_invalid(). It kind of gives you both of these. Commented Oct 24, 2013 at 13:23
  • It looks good, although the array is masked with '--'. There does not seem to be any configuration for the mask value. Cheers Commented Oct 24, 2013 at 14:06

3 Answers 3

1

To replace nan to 0, use numpy.nan_to_num:

>>> a = numpy.array([1,2,numpy.nan,4])
>>> numpy.nan_to_num(a)
array([ 1.,  2.,  0.,  4.])

Use numpy.isnan to convert nan to True, non-nan numbers to False. Then substract them from 1.

>>> numpy.isnan(a)
array([False, False,  True, False], dtype=bool)
>>> 1 - numpy.isnan(a)
array([ 1.,  1.,  0.,  1.])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that's exactly what I'm looking for :) Vikash's solution also does it fine. For the last command, I managed to do it also with the ~ sign instead of substracting one.
@carmellose, I slightly updated the answer code. You don't need to use astype if use 1 - numpy.isnan(..).
0

for first one:

numpy.nan_to_num(a)

second one:

numpy.invert(numpy.isnan(a)).astype(int)

Comments

0

To convert NaNs to zeros, use:

numpy.nan_to_num(a)

To set 1 for non-NaNs and 0 for NaNs, try:

numpy.isfinite(a)*1

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.