Your example does not produce the error:
In [120]: arr = np.zeros((4,3))
In [121]: arr[:,0] = np.random.rand(4)
In [122]: arr
Out[122]:
array([[0.81792002, 0. , 0. ],
[0.47090337, 0. , 0. ],
[0.20433628, 0. , 0. ],
[0.66201335, 0. , 0. ]])
However if you generated a different random array:
In [124]: arr[:,0] = np.random.rand(4,1)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-124-86b2b8982a84> in <module>
----> 1 arr[:,0] = np.random.rand(4,1)
ValueError: could not broadcast input array from shape (4,1) into shape (4)
arr[:,0]
produces a 1d array; indexing with a scalar reduces dimensions. MATLAB does that too - with 3d or higher (but it has a 2d lower bound).
The error is produced when trying to fit a (n,1) array into a (n,) slot. Broadcasting rules can add leading dimensions, but trailing ones have to be explicit. In numpy
leading dimensions are the outer ones (reverse of MATLAB). So a (n,)
can broadcast to (1,n)
.
Indexing with a list or array preserves dimensions, so this puts a (4,1) into a (4,1):
arr[:,[0]] = np.random.rand(4,1)
and a (3,) fits into a (1,3):
arr[[0],:] = np.random.rand(3)
A (1,n) fits into a (n,) as well:
arr[:,0] = np.random.rand(1,4)