Reputation: 103
import numpy as np
a = np.array([1,2,3,4])
print a.shape[0]
Why it will output 4
?
The array [1,2,3,4]
, it's rows should be 1
, I think , so who can explain the reason for me?
Upvotes: 1
Views: 5988
Reputation: 1
import numpy as np
X = np.array([[1,2,3], [4,5,6], [7,8,9]])
y = np.array([[9,7,8], [3,2,1], [6,5,4]])
Z = x[:2,1:] + y[1:3,:2]
print(z)
Upvotes: -1
Reputation: 1632
If you'll print a.ndim
you'll get 1. That means that a
is a one-dimensional array (has rank 1 in numpy terminology), with axis length = 4. It's different from 2D matrix with a single row or column (rank 2).
Related questions:
Upvotes: 1
Reputation: 46849
because
print(a.shape) # -> (4,)
what you think (or want?) to have is
a = np.array([[1],[2],[3],[4]])
print(a.shape) # -> (4, 1)
or rather (?)
a = np.array([[1, 2 , 3 , 4]])
print(a.shape) # -> (1, 4)
Upvotes: 2
Reputation: 388
a = np.array([1, 2, 3, 4])
by doing this, you get a a
as a ndarray, and it is a one-dimension array. Here, the shape (4,) means the array is indexed by a single index which runs from 0 to 3. You can access the elements by the index 0~3. It is different from multi-dimensional arrays.
You can refer to more help from this link Difference between numpy.array shape (R, 1) and (R,).
Upvotes: 0
Reputation: 2403
numpy arrays returns the dimensions of the array. So, when you create an array using,
a = np.array([1,2,3,4])
you get an array with 4 dimensions. You can check it by printing the shape,
print(a.shape) #(4,)
So, what you get is NOT a 1x4 matrix. If you want that do,
a = numpy.array([1,2,3,4]).reshape((1,4))
print(a.shape)
Or even better,
a = numpy.array([[1,2,3,4]])
Upvotes: 0
Reputation: 31
The shape attribute for numpy arrays returns the dimensions of the array. If a has n rows and m columns, then a.shape is (n,m). So a.shape[0] is n and a.shape[1] is m.
Upvotes: 0