Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshaping an array to 2-D by specifying only the column size

I have a vector of length, lets say 10:

foo = np.arange(2,12)

In order to convert it to a 2-D array, with lets say 2 columns, I use the command reshape with following arguments:

foo.reshape(len(foo)/2, 2)

I was wondering if there is a more elegant way/syntax to do that (may be sth like foo.reshape(,2) )

like image 366
T-800 Avatar asked Apr 12 '14 16:04

T-800


People also ask

What does reshaping an array do?

Reshaping arrays Reshaping means changing the shape of an array. The shape of an array is the number of elements in each dimension. By reshaping we can add or remove dimensions or change number of elements in each dimension.

How do you reshape an array size?

resize() can create an array of larger size than the original array. To convert the original array into a bigger array, resize() will add more elements (than available in the original array) by copying the existing elements (repeated as many times as required) to fill the desired larger size.

How do you reshape a 2D array in Python?

Use numpy. reshape() to reshape a 1D NumPy array to a 2D NumPy array. Call numpy. reshape(a, newshape) with a as a 1D array and newshape as the tuple (-1, x) to reshape the array to a 2D array containing nested arrays of x values each.

How do you reshape an array from 1D to 2D?

Convert a 1D array to a 2D Numpy array using numpy. Here, we are using np. reshape to convert a 1D array to 2 D array. You can divide the number of elements in your array by ncols.


1 Answers

You almost had it! You can use -1.

>>> foo.reshape(-1, 2)
array([[ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11]])

As the reshape docs say:

newshape : int or tuple of ints
    The new shape should be compatible with the original shape. If
    an integer, then the result will be a 1-D array of that length.
    One shape dimension can be -1. In this case, the value is inferred
    from the length of the array and remaining dimensions.
like image 77
DSM Avatar answered Oct 09 '22 09:10

DSM