简体   繁体   English

如何重塑 numpy 数组以删除所有带有 nan 的元素?

[英]How do I reshape a numpy array to remove all elements with nans?

I have a numpy array in python that is structured something like this:我在 python 中有一个 numpy 数组,其结构如下:

array([[NaN, NaN, NaN],
       [a, b, NaN],
       [c, d, e],
       [NaN, NaN, f])

Each column has the same number of non-NaN values but they start and end at different rows.每列具有相同数量的非 NaN 值,但它们在不同的行开始和结束。 I would like to end up with an array structured like:我想最终得到一个结构如下的数组:

array([a, b, e],
      [c, d, f])

(That is, with all of the NaNs removed and the shape of the array modified to fit the number of data points.) However, I'm not sure how to do this efficiently. (也就是说,删除所有 NaN 并修改数组的形状以适应数据点的数量。)但是,我不确定如何有效地做到这一点。

I tried using:我尝试使用:

x = x[~numpy.isnan(x)] 

and

x = x[numpy.logical_not(numpy.isnan(x))] 

but these both flattened the array.但这些都使阵列变平。

转置数组,过滤掉 NaN,并重新整形为其原始形状( 2是每列非 NaN 值的数量)。

x = x.T[~numpy.isnan(x.T)].reshape(-1, 2).T

Assuming what you're wanting to preserve is the number of columns:假设您要保留的是列数:

num_cols = x.shape[1]
x_trimmed = x[~numpy.isnan(x)].reshape(-1, num_cols)

You shouldn't need to transpose the array.您不需要转置数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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