Reputation: 825
I am stuck in this question. Can anybody explain me the difference between these two?
np.zeros ((1,2))
which yields
[[0. 0.]]
and
np.zeros((2,))
which yields
[0. 0.]
Upvotes: 0
Views: 1712
Reputation: 7641
For each element in the main argument of np.zeros
the function will add a new dimension to the output vector.
Your first code np.zeros ((1,2))
yields an array with two dimensions, one element in the first dimension and two elements in the second dimension, thus
[[0.]
[0.]]
The second piece of code has only one element in the main argument, which is translated to "one single dimension, two elements in that dimension". Thus, the output to your np.zeros((2,))
will be the same as the one for np.zeros(2)
:
array([0., 0.])
You could try with a third dimension to see it further:
np.zeros((1,2,1))
array([[[0.],
[0.]]])
I short, each square bracket adds to a new dimension based on the elements in the first argument of the function np.zeros
.
Upvotes: 4
Reputation: 11657
Here's how I think about it.
This answer helpfully points out that "rows" and "columns" aren't exact parallels for NumPy arrays, which can have n dimensions. Rather, each dimension, or axis, is represented by a number (the size, how many members it has) and in notation by an additional pair of square brackets.
So a 1-dimensional array of size 5 isn't a row or a column, just a 1-dimensional array. When you initialise np.zeros ((1,2))
your first dimension has size 1, and your second size 2, so you get a 1 x 2 matrix with two pairs of brackets. When you call np.zeros((2,))
it's just one dimension of size two, so you get array([0., 0.])
. I also find this confusing - hope it makes sense!
Upvotes: 1
Reputation: 900
In the first, the items would be indexed as [0][0]
and [0][1]
, and in the second, the items would be indexed by [0]
and [1]
.
A shape of (1,2)
means two dimensions, where the first dimensions happens to have only one index, i.e. it's a matrix with one row.
Upvotes: 0