In numpy
the dimensions of the resulting array vary at run time. There is often confusion between a 1d array and a 2d array with 1 column. In one case I can iterate over the columns, in the other case I cannot.
How do you solve elegantly that problem? To avoid littering my code with if
statements checking for the dimensionality, I use this function:
def reshape_to_vect(ar): if len(ar.shape) == 1: return ar.reshape(ar.shape[0],1) return ar
However, this feels inelegant and costly. Is there a better solution?
Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping. To modify the layout of a NumPy ndarray, we will be using the reshape() method.
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.
Flattening array means converting a multidimensional array into a 1D array. We can use reshape(-1) to do this.
The simplest way:
ar.reshape(-1, 1)
You could do -
ar.reshape(ar.shape[0],-1)
That second input to reshape
: -1
takes care of the number of elements for the second axis. Thus, for a 2D
input case, it does no change. For a 1D
input case, it creates a 2D
array with all elements being "pushed" to the first axis because of ar.shape[0]
, which was the total number of elements.
Sample runs
1D Case :
In [87]: ar Out[87]: array([ 0.80203158, 0.25762844, 0.67039516, 0.31021513, 0.80701097]) In [88]: ar.reshape(ar.shape[0],-1) Out[88]: array([[ 0.80203158], [ 0.25762844], [ 0.67039516], [ 0.31021513], [ 0.80701097]])
2D Case :
In [82]: ar Out[82]: array([[ 0.37684126, 0.16973899, 0.82157815, 0.38958523], [ 0.39728524, 0.03952238, 0.04153052, 0.82009233], [ 0.38748174, 0.51377738, 0.40365096, 0.74823535]]) In [83]: ar.reshape(ar.shape[0],-1) Out[83]: array([[ 0.37684126, 0.16973899, 0.82157815, 0.38958523], [ 0.39728524, 0.03952238, 0.04153052, 0.82009233], [ 0.38748174, 0.51377738, 0.40365096, 0.74823535]])
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