删除两个相同长度数组中的nan AND对应元素 [英] Delete nan AND corresponding elements in two same-length array

查看:54
本文介绍了删除两个相同长度数组中的nan AND对应元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个长度相同的列表,可以将它们转换为数组以使用

I have two lists of the same length that I can convert into array to play with the numpy.stats.pearsonr method. Now, some of the elements of these lists are nan, and can thus not be used for that method. The best thing to do in my case is to remove those elements, and the corresponding element in the other list. Is there a practical and pythonic way to do it? Example: I have

[1 2 nan 4 5 6] [1 nan 3 nan 5 6]

最后我需要

[1 5 6]

[1 5 6]

(这里的数字代表职位/指数,而不代表我正在处理的实际数字).这里最棘手的部分是要使两个列表/数组在一个数组中没有 nan ,并且在另一个数组中具有与 nan 相对应的元素,反之亦然.尽管可以肯定地通过操作数组来完成此操作,但我相信有一种清晰而又不复杂的方式可以以python方式完成.

(here the number are representative of the position/indices, not of the actual numbers I am dealing with). The tricky part here is to have both lists/arrays without nans in one array AND elements corresponding to nans in the other, and vice versa. Although it can certainly be done by manipulating the arrays, I am sure there is a clear and not overcomplicated way to do it in a pythonic way.

推荐答案

建议的重复项被接受的答案将使您半途而废.由于您已经在使用Numpy,因此应将其放入numpy数组.然后,您应该生成一个索引表达式,然后使用它来索引这两个数组.这里的索引将是形状相同的 bool 的新数组,其中每个元素都是 True (如果不是)(x中的相应元素是 nan 或相应元素y中的 nan ):

The accepted answer to proposed duplicate gets you half-way there. Since you're using Numpy already you should make these into numpy arrays. Then you should generate an indexing expression, and then use it to index these 2 arrays. Here indices will be a new array of bool of same shape where each element is True iff not (respective element in x is nan or respective element in y is nan):

>>> x
array([  1.,   2.,  nan,   4.,   5.,   6.])
>>> y
array([  1.,  nan,   3.,  nan,   5.,   6.])
>>> indices = np.logical_not(np.logical_or(np.isnan(x), np.isnan(y)))
>>> x = x[indices]
>>> y = y[indices]
>>> x
array([ 1.,  5.,  6.])
>>> y
array([ 1.,  5.,  6.])

值得注意的是,这适用于任何两个相同形状的数组.

Notably, this works for any 2 arrays of same shape.

PS,如果您知道操作数数组中的元素类型为布尔值(如此处从 isnan 返回的数组一样),则可以使用代替 logical_not | 而不是 logical_or : indices =〜(np.isnan(x)| np.isnan(y))

P.S., if you know that the element type in the operand arrays is boolean, as is the case for arrays returned from isnan here, you can use ~ instead of logical_not and | instead of logical_or: indices = ~(np.isnan(x) | np.isnan(y))

这篇关于删除两个相同长度数组中的nan AND对应元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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