简体   繁体   English

如何使用掩码对numpy矩阵进行排序?

[英]How to sort a numpy matrix using a mask?

I have two matrices A, B, Which look like this:我有两个矩阵 A、B,它们看起来像这样:

A = array([[2, 2, 1, 0, 8],
           [8, 2, 0, 3, 7],
           [3, 2, 6, 5, 3],
           [1, 4, 2, 5, 8],
           [2, 3, 7, 0, 3]])

B = array([[3, 7, 6, 8, 3],
           [0, 7, 4, 4, 3],
           [1, 2, 0, 0, 4],
           [8, 6, 6, 7, 1],
           [8, 1, 0, 4, 8]])

I am trying to sort A and B BUT I need B to be ordered with the mask from A.我正在尝试对 A 和 B 进行排序,我需要从 A 订购带有掩码的 B。

I tried this:我试过这个:

mask = A.argsort()
A = A[mask]
B = B[mask]

However the return value is a shaped (5, 5, 5) matrix然而,返回值是一个形状的 (5, 5, 5) 矩阵

The next snippet works, but is using two iterations.下一个片段有效,但使用了两次迭代。 I need something faster.我需要更快的东西。 Has anybody an Idea ?有人有想法吗?

A = [row[order] for row, order in zip(A,mask)]
B = [row[order] for row, order in zip(B,mask)]

You can use fancy indexing.您可以使用花哨的索引。 The result will be the same shape as your indices broadcasted together.结果将与您的索引一起广播的形状相同。 Your column index is already the right shape.您的列索引已经是正确的形状。 A row index of size (A.shape[0], 1) would broadcast correctly:大小为(A.shape[0], 1)的行索引将正确广播:

r = np.arange(A.shape[0]).reshape(-1, 1)
c = np.argsort(A)
A = A[r, c]
B = B[r, c]

The reason that your original index didn't work out is that you were indexing with a single dimension, which selects entire rows based on each location.原始索引不起作用的原因是您使用单个维度编制索引,该维度根据每个位置选择整行。 This would have failed if you had more columns than rows.如果列多于行,这将失败。

A simpler way would be to follow what the argsort docs suggest:一种更简单的方法是遵循argsort文档的建议:

A = np.take_along_axis(A, mask, axis=-1)
B = np.take_along_axis(B, mask, axis=-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM