Reputation: 27
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.]
Upvotes: 0
Views: 35
Reputation: 11198
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.]
Upvotes: 1
Reputation: 86
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.]
Upvotes: 4