如何交换一个给定的NumPy数组的列
在这篇文章中,让我们来讨论如何交换一个给定的NumPy数组的列。
步骤:
- 导入NumPy模块
- 创建一个NumPy数组
- 用索引交换列
- 打印最终数组
例子1:交换数组的列。
# importing Module
import numpy as np
# creating array with shape(4,3)
my_array = np.arange(12).reshape(4, 3)
print("Original array:")
print(my_array)
# swapping the column with index of
# original array
my_array[:, [2, 0]] = my_array[:, [0, 2]]
print("After swapping arrays the last column and first column:")
print(my_array)
输出 :
Original array:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
After swapping arrays the last column and first column:
[[ 2 1 0]
[ 5 4 3]
[ 8 7 6]
[11 10 9]]
例子2:用用户选择的数组的列来交换。
# Importing Module
import numpy as np
# Creating array
my_array = np.arange(12).reshape(4, 3)
print("Original Array : ")
print(my_array)
# creating function for swap
def Swap(arr, start_index, last_index):
arr[:, [start_index, last_index]] = arr[:, [last_index, start_index]]
# passing parameter into the function
Swap(my_array, 0, 1)
print(" After Swapping :")
print(my_array)
输出 :
Original Array :
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
After Swapping :
[[ 1 0 2]
[ 4 3 5]
[ 7 6 8]
[10 9 11]]