Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array that is (n,1) and (n,)

What is the difference between a numpy array (lets say X) that has a shape of (N,1) and (N,). Aren't both of them Nx1 matrices ? The reason I ask is because sometimes computations return either one or the other.

like image 635
silencer Avatar asked Jun 08 '13 01:06

silencer


People also ask

What is difference between N and N 1 in Python?

2 Answers. Show activity on this post. In Python, (10,) is a one-tuple (the , being necessary to distinguish it from the use of parentheses for grouping: (10) just means 10 ), whereas (10,1) is a pair (a 2-tuple). So np.

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])

What is 1d array in NumPy?

One dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple.

Do NumPy arrays start at 0 or 1?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


1 Answers

This is a 1D array:

>>> np.array([1, 2, 3]).shape
(3,)

This array is a 2D but there is only one element in the first dimension:

>>> np.array([[1, 2, 3]]).shape
(1, 3)

Transposing gives the shape you are asking for:

>>> np.array([[1, 2, 3]]).T.shape
(3, 1)

Now, look at the array. Only the first column of this 2D array is filled.

>>> np.array([[1, 2, 3]]).T
array([[1],
       [2],
       [3]])

Given these two arrays:

>>> a = np.array([[1, 2, 3]])
>>> b = np.array([[1, 2, 3]]).T
>>> a
array([[1, 2, 3]])
>>> b
array([[1],
       [2],
       [3]])

You can take advantage of broadcasting:

>>> a * b
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

The missing numbers are filled in. Think for rows and columns in table or spreadsheet.

>>> a + b
array([[2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]]) 

Doing this with higher dimensions gets tougher on your imagination.

like image 53
Mike Müller Avatar answered Sep 19 '22 01:09

Mike Müller