从numpy二维数组中删除NAN [英] Removing NAN's from numpy 2-D arrays

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

问题描述

类似于这个问题我想从二维numpy数组中删除一些NAN.但是,不是要删除具有NAN的整个行,而是要从数组的每一行中删除相应的元素.例如(为简单起见,使用列表格式)

Similar to this question I would like to remove some NAN's from a 2-D numpy array. However, instead of removing an entire row that has NAN's I want to remove the corresponding element from each row of the array. For example (using list format for simplicity)

x=[ [1,2,3,4],
    [2,4,nan,8],
    [3,6,9,0] ]

将成为

x=[ [1,2,4],
    [2,4,8],
    [3,6,0] ]

我可以想象使用numpy.where找出NAN在每行中出现的位置,然后使用一些循环和逻辑语句从旧数组中创建一个新数组(跳过NAN和另一个数组中的对应元素)行),但对我而言,这似乎并不是一种非常简化的处理方式.还有其他想法吗?

I can imagine using a numpy.where to figure out where in each row the NAN's appear and then use some loops and logic statements to make a new array from the old array (skipping over the NAN's and the corresponding elements in the other rows) but that to me doesn't seem to be a very streamlined way to do things. Any other ideas?

推荐答案

您可以使用布尔索引来选择仅不包含nan的那些列:

You could use boolean indexing to select only those columns which do not contain nan:

>>> x[:, ~np.isnan(x).any(axis=0)]
array([[ 1.,  2.,  4.],
       [ 2.,  4.,  8.],
       [ 3.,  6.,  0.]])

(这几乎与您链接的答案相同;只有轴已切换.)

(This is nearly identical to the answer you've linked to; only the axes have been switched.)

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

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