从对this question的回答中,我了解了如何按照一个数值数组a
的值对另一个数值数组b
的条目进行排序。
但是,这种方法需要创建几个与a
大小相同的中间数组,每个数组对应于a
的每个维度。我的一些数组非常大,这就变得不方便了。有没有一种方法可以用更少的内存来实现同样的目标?
发布于 2011-05-28 14:38:14
记录数组能满足您的需求吗?
>>> 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')
https://stackoverflow.com/questions/6162172
复制相似问题