I know that numpy array has a method called shape that returns [No.of rows, No.of columns], and shape[0] gives you the number of rows, shape[1] gives you the number of columns.
a = numpy.array([[1,2,3,4], [2,3,4,5]]) a.shape >> [2,4] a.shape[0] >> 2 a.shape[1] >> 4
However, if my array only have one row, then it returns [No.of columns, ]. And shape[1] will be out of the index. For example
a = numpy.array([1,2,3,4]) a.shape >> [4,] a.shape[0] >> 4 //this is the number of column a.shape[1] >> Error out of index
Now how do I get the number of rows of an numpy array if the array may have only one row?
Thank you
The shape attribute always returns a tuple that represents the length of each dimension. The 1-d array is a row vector and its shape is a single value sequence followed by a comma. One-d arrays don't have rows and columns, so the shape function returns a single value tuple.
reshape(-1, 1) if your data has a single feature or array. reshape(1, -1) if it contains a single sample. We could change our Series into a NumPy array and then reshape it to have two dimensions. However, as you saw above, there's an easier way to make x a 2D object.
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.
Matlab's "1D" arrays are 2D.) If you want to turn your 1D vector into a 2D array and then transpose it, just slice it with np. newaxis (or None , they're the same, newaxis is just more readable). Generally speaking though, you don't ever need to worry about this.
The concept of rows and columns applies when you have a 2D array. However, the array numpy.array([1,2,3,4])
is a 1D array and so has only one dimension, therefore shape
rightly returns a single valued iterable.
For a 2D version of the same array, consider the following instead:
>>> a = numpy.array([[1,2,3,4]]) # notice the extra square braces >>> a.shape (1, 4)
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