删除numpy数组中的NaN [英] Removing NaNs in numpy arrays

查看:259
本文介绍了删除numpy数组中的NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个包含NaN的numpy数组:

I have two numpy arrays that contains NaNs:

A = np.array([np.nan,   2,   np.nan,   3,   4])
B = np.array([   1  ,   2,     3   ,   4,  np.nan])

有什么聪明的方法使用numpy删除两个数组中的NaN,并且还删除另一个列表中相应索引上的内容?使它看起来像这样:

are there any smart way using numpy to remove the NaNs in both arrays, and also remove whats on the corresponding index in the other list? Making it look like this:

A = array([  2,   3, ])
B = array([  2,   4, ])

推荐答案

您可以做的是将2个数组加在一起,这将用NaN值覆盖(如果没有),然后使用它生成布尔掩码索引,然后使用要索引到原始numpy数组中的索引:

What you could do is add the 2 arrays together this will overwrite with NaN values where they are none, then use this to generate a boolean mask index and then use the index to index into your original numpy arrays:

In [193]:

A = np.array([np.nan,   2,   np.nan,   3,   4])
B = np.array([   1  ,   2,     3   ,   4,  np.nan])
idx = np.where(~np.isnan(A+B))
idx
print(A[idx])
print(B[idx])
[ 2.  3.]
[ 2.  4.]

来自 A + B 的输出:

In [194]:

A+B
Out[194]:
array([ nan,   4.,  nan,   7.,  nan])

编辑

正如@Oliver W.正确指出的那样, np.where 是不必要的,因为 np.isnan 将产生一个布尔索引,可用于索引到数组:

As @Oliver W. has correctly pointed out, the np.where is unnecessary as np.isnan will produce a boolean index that you can use to index into the arrays:

In [199]:

A = np.array([np.nan,   2,   np.nan,   3,   4])
B = np.array([   1  ,   2,     3   ,   4,  np.nan])
idx = (~np.isnan(A+B))
print(A[idx])
print(B[idx])
[ 2.  3.]
[ 2.  4.]

这篇关于删除numpy数组中的NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆