[英]Reverse sort of Numpy array with NaN values
I have a numpy
array with some NaN
values: 我有一个带有一些
NaN
值的numpy
数组:
>>> a
array([ 1., -1., nan, 0., nan], dtype=float32)
I can sort it in ascending or 'descending' order: 我可以按升序或'降序'排序:
>>> numpy.sort(a)
array([ -1., 0., 1., nan, nan], dtype=float32)
>>> numpy.sort(a)[::-1]
array([ nan, nan, 1., 0., -1.], dtype=float32)
However, what I want is descending order with NaN
values at the end, like this: 但是,我想要的是在最后用
NaN
值降序,如下所示:
>>> numpy.genuine_reverse_sort(a)
array([ 1., 0., -1., nan, nan], dtype=float32)
How could this be accomplished? 怎么可以实现呢? I suspect that there is no special method for this.
我怀疑没有特别的方法。
I think you're probably right -- there is no built in special method to do this. 我认为你可能是对的 - 没有内置的特殊方法来做到这一点。 But you could do it in two steps as follows by rolling your NaNs into the place you want them:
但是您可以通过将NaN滚动到您想要的位置,按照以下两个步骤执行此操作:
a = np.array([ 1., -1., np.nan, 0., np.nan], dtype=np.float32)
sa = np.sort(a)[::-1]
np.roll(sa,-np.count_nonzero(np.isnan(a)))
array([ 1., 0., -1., nan, nan], dtype=float32)
You can do the following: 您可以执行以下操作:
>>> np.concatenate((np.sort(a[~np.isnan(a)])[::-1], [np.nan] * np.isnan(a).sum()))
array([ 1., 0., -1., nan, nan])
With this fragment you reverse sort the numerical entries of the input array, and then you concatenate with the appropriate number of nan
values. 使用此片段,您可以反向排序输入数组的数字条目,然后使用适当数量的
nan
值进行连接。
You can use np.argpartition
to sort only the non-NaNs
, like so - 您可以使用
np.argpartition
仅对non-NaNs
进行排序,如下所示 -
a[np.argpartition(-a, np.arange((~np.isnan(a)).sum()) )]
Sample run - 样品运行 -
In [253]: a
Out[253]: array([ 1., -1., nan, 0., nan, 2., 4., -2., -10., nan])
In [254]: a[np.argpartition(-a, np.arange((~np.isnan(a)).sum()) )]
Out[254]: array([ 4., 2., 1., 0., -1., -2., -10., nan, nan, nan])
What about negating the values twice: 怎么样两次否定这些价值观:
>>> a = np.array([2., -1., nan, 0., nan])
>>> np.sort(a)
array([ -1., 0., 2., nan, nan])
>>> -np.sort(-a)
array([ 2., 0., -1., nan, nan])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.