我该如何"zip排序"?并行的numpy数组? [英] How can I "zip sort" parallel numpy arrays?

查看:187
本文介绍了我该如何"zip排序"?并行的numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个并行列表,并希望按照第一个中的元素顺序对其进行排序,则非常简单:

If I have two parallel lists and want to sort them by the order of the elements in the first, it's very easy:

>>> a = [2, 3, 1]
>>> b = [4, 6, 7]
>>> a, b = zip(*sorted(zip(a,b)))
>>> print a
(1, 2, 3)
>>> print b
(7, 4, 6)

如何使用numpy数组执行相同操作而又不将其解包到常规Python列表中?

How can I do the same using numpy arrays without unpacking them into conventional Python lists?

推荐答案

b[a.argsort()]应该可以解决问题.

这是它的工作方式.首先,您需要找到排序为a的排列. argsort是一种计算方法:

Here's how it works. First you need to find a permutation that sorts a. argsort is a method that computes this:

>>> a = numpy.array([2, 3, 1])
>>> p = a.argsort()
>>> p
[2, 0, 1]

您可以轻松地检查这是否正确:

You can easily check that this is right:

>>> a[p]
array([1, 2, 3])

现在将相同的排列应用于b.

Now apply the same permutation to b.

>>> b = numpy.array([4, 6, 7])
>>> b[p]
array([7, 4, 6])

这篇关于我该如何"zip排序"?并行的numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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