假设我有一个包含大量行的二维数组,以及该数组的索引对列表。我想创建一个新的2维数组,它的行是根据索引对列表生成的原始数组的行的串联。例如:
a =
1 2 3
4 5 6
7 8 9
0 0 0
indexes = [[0,0], [0,1], [2,3]]返回的数组应为:
1 2 3 1 2 3
1 2 3 4 5 6
7 8 9 0 0 0显然,我可以迭代索引列表,但我的问题是,是否有更有效的方法来做到这一点。我应该说索引列表也非常大。
发布于 2020-08-27 17:38:03
首先将索引转换为Numpy数组:
ind = np.array(indexes)然后生成如下结果:
result = np.concatenate([a[ind[:,0]], a[ind[:,1]]], axis=1)结果是:
array([[1, 2, 3, 1, 2, 3],
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 0, 0, 0]])另一个可能的公式(具有相同的结果):
result = np.concatenate([ a[ind[:,i]] for i in range(ind.shape[1]) ], axis=1)发布于 2020-08-27 17:39:22
您可以在一行中使用NumPy完成此操作:
a = np.arange(12).reshape(4, 3)
print(a)
b = [[0, 0], [1, 1], [2, 3]]
b = np.array(b)
print(b)
c = a[b.reshape(-1)].reshape(-1, a.shape[1]*b.shape[1])
print(c)
'''
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[0 0]
[1 1]
[2 3]]
[[ 0 1 2 0 1 2]
[ 3 4 5 3 4 5]
[ 6 7 8 9 10 11]]
'''发布于 2020-08-27 19:52:00
您可以使用水平堆叠np.hstack
c = np.array(indexes)
np.hstack((a[c[:,0]],a[c[:,1]]))输出:
[[1 2 3 1 2 3]
[1 2 3 4 5 6]
[7 8 9 0 0 0]]https://stackoverflow.com/questions/63613005
复制相似问题