简体   繁体   中英

How do i replace nan in 2d array with other 2d array value

For example, I have on 2d array named c.

>>> c = numpy.array([[1,np.nan,3],[4,5,6],[7,8,9]])
>>> c
array([[  1.,  nan,   3.],
       [  4.,   5.,   6.],
       [  7.,   8.,   9.]])

other named as b.

>>> b
array([[1, 0, 1],
       [0, 0, 0],
       [1, 0, 1]])

In in the array index c[0][1] there is nan i want to replace it with b[0][1]. without using for loop.

Is there any method in numpy which will enable me to do so?

I want the result to look like following.

>>> c
array([[ 1.,  0.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]])

You can use numpy.isnan ( http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.isnan.html )

c = numpy.array([[1,numpy.nan,3],[4,5,6],[7,8,9]])
b = numpy.array([[1,0,1],[0,0,0],[1,0,1]])
ind = numpy.isnan(c)
c[ind] = b[ind]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM