ndarray
的 reshape
方法用于改变 NumPy 数组的形状,而不改变其数据。通过使用 reshape
方法,可以将数组重新组织为具有不同维数的形状,但新的形状必须与原始数据的总元素数量相同。
直接通过示例来进行理解。
示例一:
import numpy as np
# 创建一个 1x6 的数组
arr = np.array([1, 2, 3, 4, 5, 6])
print("Original array:")
print(arr)
# 将其重塑为 2x3 的数组
reshaped_arr = arr.reshape(2, 3)
print("Reshaped array (2x3):")
print(reshaped_arr)
# 将其重塑为 3x2 的数组
reshaped_arr2 = arr.reshape(3, 2)
print("Reshaped array (3x2):")
print(reshaped_arr2)
输出:
Original array:
[1 2 3 4 5 6]
Reshaped array (2x3):
[[1 2 3]
[4 5 6]]
Reshaped array (3x2):
[[1 2]
[3 4]
[5 6]]
示例一将元来一行六列的数组通过reshape方法重新组织成了两行三列的数组和三行两列的数组。
示例二(使用 -1
自动推断维度):
在 reshape
方法中,可以使用 -1
来让 NumPy 自动推断某一个维度的大小。只要其他维度的大小能确定总元素数目,NumPy 就能计算出 -1
对应的维度大小。
import numpy as np
# 创建一个 1x6 的数组
arr = np.array([1, 2, 3, 4, 5, 6])
print("Original array:")
print(arr)
# 使用 -1 让 NumPy 自动推断维度
reshaped_arr = arr.reshape(2, -1) # 自动推断为 (2, 3)
print("Reshaped array (2, -1):")
print(reshaped_arr)
reshaped_arr2 = arr.reshape(-1, 2) # 自动推断为 (3, 2)
print("Reshaped array (-1, 2):")
print(reshaped_arr2)
输出:
Original array:
[1 2 3 4 5 6]
Reshaped array (2, -1):
[[1 2 3]
[4 5 6]]
Reshaped array (-1, 2):
[[1 2]
[3 4]
[5 6]]
注意事项
-
元素总数不变:
reshape
不会改变数组的元素总数。新的形状必须与原始形状的元素总数相同,否则会引发错误。 -
返回新数组:
reshape
返回一个新的数组,原始数组保持不变。 -
多维数组:
reshape
方法不仅适用于一维数组,也可以用于多维数组。例如,将二维数组重塑为三维数组。
示例 - 将二维数组重塑为三维数组
import numpy as np
# 创建一个 2x6 的二维数组
arr = np.array([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]])
print("Original 2x6 array:")
print(arr)
# 将其重塑为 3x2x2 的三维数组
reshaped_arr = arr.reshape(3, 2, 2)
print("Reshaped array (3x2x2):")
print(reshaped_arr)
输出:
Original 2x6 array:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Reshaped array (3x2x2):
[[[ 1 2]
[ 3 4]]
[[ 5 6]
[ 7 8]]
[[ 9 10]
[11 12]]]
通过 reshape
方法,可以灵活地调整数组的形状,以满足不同的数据处理需求。