numpy.reshape用法
时间: 2023-10-30 12:07:40 浏览: 90
numpy.reshape是用来改变数组的形状的函数。它的语法如下:
numpy.reshape(arr, newshape, order='C')
其中,arr表示要改变形状的数组,newshape表示新的形状,可以是一个元组或一个整数,order表示数组的存储顺序,可以是'C'或'F',分别表示行优先和列优先。如果没有指定order参数,则默认为'C'。
下面是一些使用numpy.reshape的示例:
1. 将一维数组转换为二维数组:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
arr_reshape = np.reshape(arr, (2, 3))
print(arr_reshape)
输出:
[[1 2 3]
[4 5 6]]
2. 将二维数组转换为一维数组:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr_reshape = np.reshape(arr, (6,))
print(arr_reshape)
输出:
[1 2 3 4 5 6]
3. 将三维数组转换为二维数组:
import numpy as np
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
arr_reshape = np.reshape(arr, (2, 4))
print(arr_reshape)
输出:
[[1 2 3 4]
[5 6 7 8]]
4. 将二维数组的存储顺序改为列优先:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr_reshape = np.reshape(arr, (3, 2), order='F')
print(arr_reshape)
输出:
[[1 5]
[4 2]
[3 6]]
阅读全文
相关推荐


















