将 "nan" 移动到 python 中数组的开头

Shift "nan" to the beginning of an array in python

如果我有一个带有 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.]])

这是一种方法:

# 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.]])