Meaning of -1 in numpy reshape
When reshaping a 2D array into a 1D array using numpy's reshape function, -1 can be specified as one of the dimensions. Surprisingly, this does not indicate the last element as it usually does when indexing an array.
Instead, -1 represents an unknown dimension. numpy calculates the missing dimension by multiplying the total number of elements in the array by the known dimension.
For example, consider the 2D array:
a = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8]])
Reshaping it using reshape(-1), we get:
a.reshape(-1) array([[1, 2, 3, 4, 5, 6, 7, 8]])
The resulting array is 1D, with all the elements from the original array concatenated.
This feature is particularly useful when dealing with arrays of unknown dimensions. By specifying -1, numpy automatically calculates the missing dimension based on the array's length and the dimensions provided.
The above is the detailed content of What is the Meaning of -1 in NumPy Reshape?. For more information, please follow other related articles on the PHP Chinese website!