1 Introduction
Change the shape of an array without changing the original array
2. Grammar
a = np.reshape(mat, newshape, order = 'C')
a : new array of newshape shape
mat : original array
newshape: (1, 2)/ 1, 2 can be changed to an array of 1 row and 2 columns
order: The rules for reading the original array, the default is C (C row first, F in a certain way, but not column first!)
The order is temporarily understood in this way.
3. use
- b = np.reshape(a, newshape)
- b = a.reshape(newshape)
key: There can be a parameter -1 in newshape, which means fuzzy speculation, such as (-1, 2) I don’t care if you have rows, just modify it to a two-dimensional array with 2 columns; such as (3, -1) I don’t care about you There are several columns, just modify it to a two-dimensional array of 3 rows
3.1 Reference example of order
row first:
import numpy as np
a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 修改为1,行12列数组,顺序读取
b = a.reshape(1, 12, order='C')
print("修改后:")
print(b)
F way to read
import numpy as np
a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 修改为1行12列,按列优先读取
b = a.reshape(1, 12, order='F')
print("修改后:")
print(b)
non-column-first
3.2 Actual usage (the general order is the default value)
given shape
import numpy as np
# 3行4列的二维数组
a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 此时中间只剩newshape,2行6列
b = a.reshape(2,6)
print("修改后:")
print(b)
fuzzy speculation
import numpy as np
# 3行4列的二维数组
a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 此时中间只剩newshape,修改为6行的数组就行,多少列我不知道
b = a.reshape(6, -1)
print("修改后:")
print(b)
fuzzy speculation
import numpy as np
# 3行4列的二维数组
a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 此时中间只剩newshape,修改为3列的数组就行,多少行我不知道
b = a.reshape(-1, 3)
print("修改后:")
print(b)
fuzzy speculation
import numpy as np
# 3行4列的二维数组
a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 此时中间只剩newshape,修改为3行2列的子数组,多少行我不知道
b = a.reshape((-1, 3, 2))
print("修改后:")
print(b)
key: At the beginning of the array, the number of square brackets is the number of dimensions. The original array is a two-dimensional array, and the modified array is a three-dimensional array
The above is the usage of reshape, and it may be added in the future. Welcome to discuss in the comment area!