1
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?

mochi
  • 1,549
  • 11
  • 23
David
  • 103
  • 6

5 Answers5

2

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)
hiro protagonist
  • 36,147
  • 12
  • 68
  • 86
1

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

More on ranks

Related questions:

Community
  • 1
  • 1
alexisrozhkov
  • 1,595
  • 9
  • 18
0

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.

gauri
  • 21
  • 4
0

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]])
Chandan Purohit
  • 1,708
  • 1
  • 14
  • 11
0
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,).

Community
  • 1
  • 1
Peiqin
  • 330
  • 3
  • 11