I am reading source code of an open source project recently. When the programmer wanted to convert a row vector like array([0, 1, 2])
to a column vector like array([[0], [1], [2]])
, np.reshape(x, (-1,1))
was used.
In the comment, it says reshape is necessary to preserve the data contiguity against vs [:, np.newaxis]
that does not.
I tried the two ways, it seems like they will return the same results. Then what does the data contiguity preservation mean here?
The numpy. reshape() function shapes an array without changing the data of the array.
Simply put, numpy. newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus, 1D array will become 2D array.
Artturi Jalli. In NumPy, -1 in reshape(-1) refers to an unknown dimension that the reshape() function calculates for you. It is like saying: “I will leave this dimension for the reshape() function to determine”. A common use case is to flatten a nested array of an unknown number of elements to a 1D array.
reshape() function allows us to reshape an array in Python. Reshaping basically means, changing the shape of an array. And the shape of an array is determined by the number of elements in each dimension. Reshaping allows us to add or remove dimensions in an array.
Both ways return views of the exact same data, therefore the 'data contiguity' is likely a non-issue as the data is not change, only the view is changed. See Numpy: use reshape or newaxis to add dimensions.
However there might be a practical advantage of using .reshape((-1,1))
, as it will reshape the array into 2d array regardless of the original shape. For [:, np.newaxis]
, the result will depend on the original shape of the array, considering these:
In [3]: a1 = np.array([0, 1, 2])
In [4]: a2 = np.array([[0, 1, 2]])
In [5]: a1.reshape((-1, 1))
Out[5]:
array([[0],
[1],
[2]])
In [6]: a2.reshape((-1, 1))
Out[6]:
array([[0],
[1],
[2]])
In [7]: a1[:, np.newaxis]
Out[7]:
array([[0],
[1],
[2]])
In [8]: a2[:, np.newaxis]
Out[8]: array([[[0, 1, 2]]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With