【问题标题】:Shift "nan" to the beginning of an array in python [duplicate]在python中将“nan”移到数组的开头[重复]
【发布时间】:2020-11-11 19:51:12
【问题描述】:

如果我有一个带有 nan 的数组,它看起来像这样:

array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0., nan, nan],
       [ 0.,  1.,  3., nan],
       [ 0.,  2.,  4.,  7.],
       [ 0., nan,  2., nan],
       [ 0.,  4., nan, nan]])

如何在不改变形状的情况下将所有 nan 移到数组的开头? 像这样的东西:

array([[ 0.,  0.,  0.,  0.],
       [ nan, nan, 0.,  0.],
       [ nan, 0.,  1.,  3.],
       [ 0.,  2.,  4.,  7.],
       [ nan, nan, 0.,  2.],
       [ nan, nan, 0.,  4.]])

【问题讨论】:

  • 很酷的问题。编写解决方案并不难,但我期待利用 numpy 获得高性能答案。

标签: python arrays python-3.x numpy nan


【解决方案1】:

这是一种方法:

# find the position of nan itms in "a"
In [19]: mask = np.isnan(a)                                                                                                                                                                                 
# put them at the beginning by sorting the mask in a descending order
In [20]: nan_pos = np.sort(mask)[:,::-1]                                                                                                                                                                    
# the new position of non_non items is the inverse of non-mask sorted ascending 
In [21]: not_nan_pos = np.sort(~mask)                                                                                                                                                                       

In [22]: emp = np.empty(a.shape)                                                                                                                                                                            

In [23]: emp[nan_pos] = np.nan                                                                                                                                                                              

In [24]: emp[not_nan_pos] = a[~mask]                                                                                                                                                                        

In [25]: emp                                                                                                                                                                                                
Out[25]: 
array([[ 0.,  0.,  0.,  0.],
       [nan, nan,  0.,  0.],
       [nan,  0.,  1.,  3.],
       [ 0.,  2.,  4.,  7.],
       [nan, nan,  0.,  2.],
       [nan, nan,  0.,  4.]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2021-11-27
    • 2013-07-28
    • 1970-01-01
    • 2014-05-16
    • 2017-12-15
    • 2014-02-12
    • 2014-07-11
    相关资源
    最近更新 更多