Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

np.reshape(x, (-1,1)) vs x[:, np.newaxis]

Tags:

python

numpy

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?

like image 213
HannaMao Avatar asked Sep 21 '17 01:09

HannaMao


People also ask

What does NP reshape mean?

The numpy. reshape() function shapes an array without changing the data of the array.

What does Newaxis do in NumPy?

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.

What is the use of reshape (- 1 1 in Python?

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.

What is the use of reshape () method?

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.


Video Answer


1 Answers

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]]])
like image 116
CT Zhu Avatar answered Oct 05 '22 23:10

CT Zhu