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)
)
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.
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.
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.
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.
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.
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