使用较少的内存沿特定轴对另一个数组排序一个numpy数组 [英] Sort a numpy array by another array, along a particular axis, using less memory

查看:81
本文介绍了使用较少的内存沿特定轴对另一个数组排序一个numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从答案到这个问题,我学习了如何通过沿特定轴的另一个numpy数组b的值.

From the answer to this question, I learned how to sort the entries of one numpy array a by the values of another numpy array b, along a particular axis.

但是,此方法需要创建几个与a大小相同的中间数组,每个a维都需要一个.我的一些数组很大,这很不方便.有没有办法实现使用更少内存的相同目标?

However, this method requires the creation of several intermediate arrays that are the same size as a, one for each dimension of a. Some of my arrays are quite large, and this becomes inconvenient. Is there a way to accomplish the same goal that uses less memory?

推荐答案

记录数组是否可以满足您的目的?

Would a record array serve your purposes?

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

一种生成耦合数组的更简洁的方法:

A cleaner way to generate the coupled array:

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

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

这篇关于使用较少的内存沿特定轴对另一个数组排序一个numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆