We know that it numpy.ndarray.reshape()
is used to change numpy
the 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 6
one-dimensional array of length into a two-dimensional array of size (2, 3)
, where the 2
representative 2
row corresponds to the y axis, the 3
representative 3
column corresponds to the x
axis.
However, sometimes we will use -1
this 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 reshape
the first parameter to -1
, we still get an (2, 3)
array of size , in fact, here, the -1
representative means 6 / 3 =2
, which 6
is the length of the one-dimensional array to be shaped , which is 3
specified 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 python
will 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~