在Python中,使用NumPy库的`reshape`函数可以改变数组的形状,而不改变其数据内容。`reshape`函数的基本语法如下:
numpy.reshape(a, newshape, order='C')
其中:
`a` 是需要重塑的数组。
`order` 参数是可选的,用于指定数组在内存中的存储顺序,默认为 `'C'`,表示按行连续顺序存储。
示例用法
1. 将一维数组重塑为多维数组:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
reshaped_arr = np.reshape(arr, (3, 4))
print(reshaped_arr)
输出:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
2. 将一维数组重塑为具有不同维度的多维数组:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
reshaped_arr = np.reshape(arr, (2, 2, 2))
print(reshaped_arr)
输出:
[[[ 1 2]
[ 3 4]]
[[ 5 6]
[ 7 8]]]
3. 使用 `-1` 自动计算形状:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
reshaped_arr = np.reshape(arr, (-1, 3))
print(reshaped_arr)
输出:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
请注意,`newshape` 中的值之和必须等于原数组的元素总数,否则会抛出错误。如果 `newshape` 中有一个值设为 `-1`,NumPy 会根据剩余维度的元素数量自动计算该值