基于二维Numpy数组索引的Numpy二维数组排列方法是什么?

4
import numpy as np
x = np.array([[1,2 ,3], [9,8,7]])
y = np.array([[2,1 ,0], [1,0,2]])

x[y]

期望输出:

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

如果x和y是一维数组,那么x[y]可以实现。那么对于二维数组,最符合numpy或最pythonic或最高效的方法是什么?
2个回答

2
你需要定义相应的行索引。
一种方法是:
>>> x[np.arange(x.shape[0])[..., None], y]
array([[3, 2, 1],
       [8, 9, 7]])

1
你可以通过 y 计算线性索引,然后使用这些索引从 x 中提取特定元素,如下所示 -
# Linear indices from y, using x's shape
lin_idx = y + np.arange(y.shape[0])[:,None]*x.shape[1]

# Use np.take to extract those indexed elements from x
out = np.take(x,lin_idx)

示例运行 -

In [47]: x
Out[47]: 
array([[1, 2, 3],
       [9, 8, 7]])

In [48]: y
Out[48]: 
array([[2, 1, 0],
       [1, 0, 2]])

In [49]: lin_idx = y + np.arange(y.shape[0])[:,None]*x.shape[1]

In [50]: lin_idx  # Compare this with y
Out[50]: 
array([[2, 1, 0],
       [4, 3, 5]])

In [51]: np.take(x,lin_idx)
Out[51]: 
array([[3, 2, 1],
       [8, 9, 7]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接