首页 > 解决方案 > 相对于另一个数组对数组进行排序

问题描述

我在我的程序中使用了一些数据,如果我有一些排序问题,这对我来说需要更长的时间。所以我在这里提到了一个例子,我想得到一个解决方案。

import numpy as np 
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
B = np.array([[4,5,6,7],[7,8,9,4],[1,2,3,2]])
# Need to apply some sort function
C = sort(B[:,0:3] to be sorted with respect to A)
print(C)

我有两个 numpy 数组,我希望数组 B 的前 3 列相对于数组 A 进行排序。

我希望 C 的输出为

[[1,2,3,2],[4,5,6,7],[7,8,9,4]]

是否有任何 numpy 方法或任何其他 python 库可以做到这一点。

期待一些答案

问候

阿迪提亚

标签: pythonpandaslistnumpysorting

解决方案


这仅在使用第一列时有效:

_, indexer, _ = np.intersect1d(B[:,:1], A[:,:1], return_indices=True)

B[indexer]

array([[1, 2, 3, 2],
   [4, 5, 6, 7],
   [7, 8, 9, 4]])

显然,上述解决方案仅在值唯一的情况下才有效(感谢@AadithyaSaathya。

如果我们要使用所有 A,我们可以使用 itertools 的产品功能:

from itertools import product
indexer = [B[0] 
           for A,B 
           in
           product(enumerate(A), enumerate(B[:,:3]))
           if np.all(np.equal(A[-1], B[-1]))]

B[indexer]


array([[1, 2, 3, 2],
       [4, 5, 6, 7],
       [7, 8, 9, 4]])

推荐阅读