使用更少内存按特定轴根据另一个数组排序numpy数组

1 投票
1 回答
2307 浏览
提问于 2025-04-16 18:31

从对这个问题的回答中,我了解到如何根据另一个numpy数组b的值,沿着特定的轴对一个numpy数组a的条目进行排序。

不过,这种方法需要创建几个与a大小相同的中间数组,每个维度都需要一个。有些数组比较大,这样就不太方便了。有没有办法用更少的内存达到同样的目的呢?

1 个回答

2

你觉得使用记录数组能满足你的需求吗?

>>> a = numpy.zeros((3, 3, 3))
>>> a += numpy.array((1, 3, 2)).reshape((3, 1, 1))
>>> b = numpy.arange(3*3*3).reshape((3, 3, 3))
>>> c = numpy.array(zip(a.flatten(), b.flatten()), dtype=[('f', float), ('i', int)]).reshape(3, 3, 3)
>>> c.sort(axis=0)
>>> c['i']
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])

这里有一种更简洁的方法来生成配对数组:

>>> c = numpy.rec.fromarrays([a, b], dtype=[('f', float), ('i', int)])

或者

>>> c = numpy.rec.fromarrays([a, b], names='f, i')

撰写回答