0

I'm trying to set elemnts of array1 to nan based on elements of array2 which are nan.

The following is my code (which isn't working)

I would greatly appreciate assistance :)

array1 = np.array([1.,1.,1.,1.,1.,1.,1.,1.,1.,1.])
array2 = np.array([2.,2.,2.,2.,np.nan,np.nan,np.nan,2.,2.,2.])

#I want to create:
#[1.,1.,1.,1.,np.nan,np.nan,np.nan,1.,1.,1.]

# I've tried:
array1[array2 == np.nan] = np.nan
print(array1)
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

2 Answers 2

4

Use np.isnan.

import numpy as np
array1 = np.array([1.,1.,1.,1.,1.,1.,1.,1.,1.,1.])
array2 = np.array([2.,2.,2.,2.,np.nan,np.nan,np.nan,2.,2.,2.])
array1[np.isnan(array2)] = np.nan
print(array1)

Output is as desired:

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

Comments

1

You can use numpy.argwhere to find the indices with np.nan and finally use those indices to change the value of array1.

import numpy as np

array1 = np.array([1.,1.,1.,1.,1.,1.,1.,1.,1.,1.])
array2 = np.array([2.,2.,2.,2.,np.nan,np.nan,np.nan,2.,2.,2.])

inds = np.argwhere(np.isnan(array2))
print(inds)
array1[inds] = np.nan

print(array1)
[[4]
 [5]
 [6]]
[ 1.  1.  1.  1. nan nan nan  1.  1.  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.