本文介绍了如何过滤出包含NaN的子数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们假设一个形状为(n,5,2)
的数组,该数组在随机位置包含NaN
,由以下代码生成:
Let's assume an array of shape (n,5,2)
which contains NaN
s at random places, generated by the following code:
n = 10
arr = np.random.rand(n, 5, 2)
# replace some values by nan
arr = arr.ravel()
index_array = np.arange(arr.size)
np.random.shuffle(index_array)
arr[index_array[:5]] = np.nan
arr = arr.reshape(n, 5, 2)
如何有效过滤该数组,以便仅保留不包含NaN
的那些arr[i]
?然后将得到的形状为(m,5,2)
和m<=n
.
How can I efficiently filter this array such that only those arr[i]
s are kept which don't contain NaN
s? The resulting shape would then be (m,5,2)
with m<=n
.
推荐答案
无需重塑任何内容:
has_nans = np.isnan(arr).any(axis=(-1,-2))
has_nans
array([False, False, False, True, True, True, False, False, False, True], dtype=bool)
>>> arr = arr[~has_nans]
>>> arr.shape
(6, 5, 2)
较旧版本的numpy,您需要执行以下操作:
Older versions of numpy you will need to do something like the following:
has_nans = np.isnan(arr).any(axis=-1).any(axis=-1)
这篇关于如何过滤出包含NaN的子数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!