python - 对 numpy 数组的非零元素进行排序并获取它们的索引

标签 python sorting numpy

我有一个 numpy 数组:

x =   numpy.array([0.1, 0, 2, 3, 0, -0.5])

我想得到一个数组 y,它包含已排序的 x 的非零元素和 idx,它是 x 的对应索引。

例如,对于上述示例,y 将为 [3, 2, 0.1, -0.5],idx 将为 [3, 2, 0, 5]。我更喜欢一种可以扩展到二维数组而无需遍历 x 行的方法。

如果我有一个二维的例子

x = [[0.1, 0, 2, 3, 0, -0.5],
     [1, 0, 0, 0, 0, 2 ]] 

我想要一个

y =[[3, 2, 0.1, -0.5],[2,1]] and 
idx = [[3, 2, 0, 5], [5, 0]].

最佳答案

这是分别解决1D2D 情况的两种向量化方法 -

def sort_nonzeros1D(x):
    sidx = np.argsort(x)
    out_idx = sidx[np.in1d(sidx, np.flatnonzero(x!=0))][::-1]
    out_x = x[out_idx]
    return out_x, out_idx

def sort_nonzeros2D(x):
    x1 = np.where(x==0, np.nan, x)
    sidx = np.argsort(x1,1)[:,::-1]

    n = x.shape[1]
    extent_idx = (x==0).sum(1)
    valid_mask = extent_idx[:,None] <= np.arange(n)
    split_idx = (n-extent_idx[:-1]).cumsum()

    out_idx = np.split(sidx[valid_mask], split_idx)
    y = x[np.arange(x.shape[0])[:,None], sidx]
    out_x = np.split(y[valid_mask], split_idx)
    return out_x, out_idx

样本运行

1D 案例:

In [461]: x
Out[461]: array([ 0.1,  0. ,  2. ,  3. ,  0. , -0.5])

In [462]: sort_nonzeros1D(x)
Out[462]: (array([ 3. ,  2. ,  0.1, -0.5]), array([3, 2, 0, 5]))

2D 案例:

In [470]: x
Out[470]: 
array([[ 0.1,  0. ,  2. ,  3. ,  0. , -0.5],
       [ 1. ,  0. ,  0. ,  0. ,  0. ,  2. ],
       [ 7. ,  0. ,  2. ,  5. ,  1. ,  0. ]])

In [471]: sort_nonzeros2D(x)
Out[471]: 
([array([ 3. ,  2. ,  0.1, -0.5]),
  array([ 2.,  1.]),
  array([ 7.,  5.,  2.,  1.])],
 [array([3, 2, 0, 5]), array([5, 0]), array([0, 3, 2, 4])])

关于python - 对 numpy 数组的非零元素进行排序并获取它们的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42212300/

相关文章:

python - 如何创建一个宏来遍历 Pandas Dataframe 中的所有列?

c - 按字母顺序对书名进行排序

python - 递归选择排序以返回python中的降序列表

python - Numpy.savetxt() 函数

python - 如何加快 numpy.append 速度

python - 棋盘结构

python - 执行笛卡尔积时如何减少内存消耗?

python - 列表作为字典的键

java - 按车牌号比较汽车对象列表

python - newArray = myNumpyArray[:, 0] 是什么意思?