Detailed usage of reshape function in python

Detailed usage of reshape function in python

reshape function
The reshape function is a function in the Numpy library that can be used to change the shape of an array, such as converting a two-dimensional array into a three-dimensional array.

import numpy as np
# 创建一个二维数组,形状为(4, 6)
a = np.array([[1, 2, 3, 4, 5, 6],
              [7, 8, 9, 10, 11, 12],
              [13, 14, 15, 16, 17, 18],
              [19, 20, 21, 22, 23, 24]])
# 将二维数组a转换成一个三维数组,形状为(2, 3, 4)
b = np.reshape(a, (2, 3, 4))
print(a.shape)    # 输出(4, 6)
print(b.shape)    # 输出(2, 3, 4)
print(b)

Program running results:

The following are the specific implementation details of the reshape function:

numpy.reshape(array, newshape, order='C')
  • Among them, array indicates the array whose shape is to be changed, newshape indicates the new shape, and order indicates the storage order of elements in the new array (optional, the default is 'C', that is, stored in rows).
  • When the product of the elements in the newshape is not equal to the product of the elements in the original array, a ValueError exception will be thrown (of course this will not work, there is no way to deal with the empty or extra); when the product of the elements in the newshape and When the products of the elements in the original array are equal, the reshape function will rearrange the elements in the original array in the order specified by the order parameter to generate a new array. (Take the example in the code above as 4X6=2X3X4)

The specific implementation of this function is as follows:

  1. First, build a new empty array based on the elements in newshape to store the rearranged elements.
  2. Then, in the order specified by the order parameter, the elements in the original array are copied to the new array one by one. The commonly used storage order is 'C' (stored by row) and 'F' (stored by column).
  3. Finally, the new array is returned.

The reshape function can be used to change the shape of a multidimensional array, such as converting a two-dimensional array to a three-dimensional array, or converting a three-dimensional array to a two-dimensional array. But it should be noted that the reshape function will not change the number of elements and data types in the array, only the shape of the array.
In short, the reshape function is a very practical function that can be used to convert an array into an array of any shape. When using the reshape function, care must be taken to ensure that the product of elements in newshape is equal to the product of elements in the original array, so as to ensure that the rearranged array will not lose elements.

Guess you like

Origin blog.csdn.net/change_xzt/article/details/129999062