如何使用给定的索引位置重新排列 2D NumPy 数组的列?
在本文中,我们将学习如何使用给定的索引位置重新排列给定 numpy 数组的列。这里的列使用给定的索引重新排列。为此,我们可以简单地将列值存储在列表中,并根据给定的索引列表排列这些值,但这种方法非常昂贵。因此,通过使用 numpy 数组的概念,可以在最短的时间内轻松完成。
例子 :
Arr = [[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]] and i = [2, 4, 0, 3, 1]
then output is [[3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2], [3, 5, 1, 4, 2]].
Here, i[0] = 2 i.e; 3rd column so output = [[3],[3],[3],][3],[3]].
i[1] = 4 i.e; 5th column so output = [[3,5],[3,5],[3,5],][3,5],[3,5]].
i[2] = 0 i.e; 1st column so output = [[3,5,1],[3,5,1],[3,5,1],][3,5,1],[3,5,1]].
i[3] = 3 i.e; 4th column so output = [[3,5,1,4],[3,5,1,4],[3,5,1,4],][3,5,1,4],[3,5,1,4]].
i[4] = 1 i.e; 2nd column so output = [[3,5,1,4,2],[3,5,1,4,2],[3,5,1,4,2],][3,5,1,4,2],[3,5,1,4,2]].
下面是一个例子的实现:
Python3
# importing package
import numpy
# create a numpy array
arr = numpy.array([[1,2,3,4,5],
[1,2,3,4,5],
[1,2,3,4,5],
[1,2,3,4,5],
[1,2,3,4,5]
])
# view array
print(arr)
# declare index list
i = [2,4,0,3,1]
# create output
output = arr[:,i]
# view output
print(output)
输出 :
[[1 2 3 4 5]
[1 2 3 4 5]
[1 2 3 4 5]
[1 2 3 4 5]
[1 2 3 4 5]]
[[3 5 1 4 2]
[3 5 1 4 2]
[3 5 1 4 2]
[3 5 1 4 2]
[3 5 1 4 2]]