numpy.ndarray.reshape() function parameter problem

We know that it numpy.ndarray.reshape()is used to change numpythe shape of the array, but its parameters will have some special uses, here we will explain further. code show as below:

import numpy as np


class Debug:
    def __init__(self):
        self.array1 = np.ones(6)

    def mainProgram(self):
        print("The value of array1 is: ")
        print(self.array1)
        print("The array2 is: ")
        array2 = self.array1.reshape(2, 3)
        print(array2)


if __name__ == '__main__':
    main = Debug()
    main.mainProgram()
"""
The value of array1 is: 
[1. 1. 1. 1. 1. 1.]
The array2 is: 
[[1. 1. 1.]
 [1. 1. 1.]]
"""

Here we see that we have turned a 6one-dimensional array of length into a two-dimensional array of size (2, 3), where the 2representative 2row corresponds to the y axis, the 3representative 3column corresponds to the xaxis.

However, sometimes we will use -1this parameter in reshape . When using this parameter, it will be very simple to reshape the array. code show as below:

class Debug:
    def __init__(self):
        self.array1 = np.ones(6)

    def mainProgram(self):
        print("The value of array1 is: ")
        print(self.array1)
        print("The array2 is: ")
        array2 = self.array1.reshape(-1, 3)
        print(array2)


if __name__ == '__main__':
    main = Debug()
    main.mainProgram()
"""
The value of array1 is: 
[1. 1. 1. 1. 1. 1.]
The array2 is: 
[[1. 1. 1.]
 [1. 1. 1.]]
"""

We can see that when we change reshapethe first parameter to -1, we still get an (2, 3)array of size , in fact, here, the -1representative means 6 / 3 =2, which 6is the length of the one-dimensional array to be shaped , which is 3specified by us The dimension of a two-dimensional array in one direction. The advantage of this is that when the amount of data is relatively large, we only need to specify the size in one dimension when reshaping the two-dimensional array, and the size in the other dimension pythonwill be automatically calculated for us.

If you find it useful, please raise your hand to give a like and let me recommend it to more people~

Guess you like

Origin blog.csdn.net/u011699626/article/details/109006973