Hanfei Sun
Hanfei Sun

Reputation: 47061

what's the difference between (4,) and (4,1) for the shape in Numpy?

I have two ndarray A and B, one has the shape (4,) and another (4,1).

When I want to calculate the cosine distance using this, it throws some exceptions that complains the two objects are not aligned

Does anyone have ideas about this? Thanks!

Upvotes: 5

Views: 7621

Answers (2)

zam_22
zam_22

Reputation: 21

An ndarray having shape equal to (4,) is a 1-Dimensional NumPy array.
Example,

>>> import numpy as np
>>> array_1 = np.random.randint(0,10,4)
>>> array_1
array([9, 3, 0, 4])
>>> array_1.shape    # shape of array_1
(4,)
>>> array_1.ndim    # number of dimensions in array_1
1

An ndarray having shape equal to (4,1) is a 2-Dimensional NumPy array having 4 rows and 1 column. It is also called a column vector.
Example,

>>> array_2 = np.random.randint(0, 10, (4,1))
>>> array_2
array([[7],
       [0],
       [5],
       [8]])
>>> array_2.shape    # shape of array_2
(4, 1)
>>> array_2.ndim    # number of dimensions in array_2
2

An ndarray having shape equal to (1,4) is a 2-Dimensional NumPy array having 1 row and 4 columns. It is also called a row vector.
Example,

>>> array_3 = np.random.randint(0, 10, (1,4))
>>> array_3
array([[0, 5, 2, 6]])
>>> array_3.shape    # shape of array_3
(1, 4)
>>> array3.ndim    # number of dimensions in array_3
2

As a general rule, the number of [ (opening square brackets) at the beginning of the array or the number of ] (closing square brackets) at the end of the array represents the number of dimensions in the array.
For Example,
[1, 2, 3] is a 1-D array, [[1,2,3], [4,5,6]] is a 2-D array, and so on.

Upvotes: 0

mgilson
mgilson

Reputation: 309881

One is a 1-dimensional array, the other is a 2-dimensional array.

Example:

>>> import numpy as np
>>> a = np.arange(4).reshape(4,1)
>>> a
array([[0],
       [1],
       [2],
       [3]])
>>> a.ravel()
array([0, 1, 2, 3])
>>> a.squeeze()
array([0, 1, 2, 3])
>>> a[:,0]
array([0, 1, 2, 3])
>>>
>>> a[:,0].shape
(4,)

Upvotes: 9

Related Questions