Reputation: 5921
Having two arrays like:
a = np.zeros((3, 4), dtype=int)
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
b = np.ones((2, 3), dtype=int)
[[1 1 1]
[1 1 1]]
How to assign from a source array (b
) to the entries in the destination array (a
) that are present in source ?
The resulting array should then be:
[[1 1 1 0]
[1 1 1 0]
[0 0 0 0]]
Upvotes: 2
Views: 53
Reputation: 476567
You can simply obtain the shape
of b
like:
m,n = b.shape
and then use slices to set the elements in a
:
a[:m,:n] = b
This generates:
>>> m,n = b.shape
>>> a[:m,:n] = b
>>> a
array([[1, 1, 1, 0],
[1, 1, 1, 0],
[0, 0, 0, 0]])
In case a
and b
have the same but an arbitrary number of dimensions, we can use the following generator:
a[tuple(slice(mi) for mi in b.shape)] = b
which results again in:
>>> a[tuple(slice(mi) for mi in b.shape)] = b
>>> a
array([[1, 1, 1, 0],
[1, 1, 1, 0],
[0, 0, 0, 0]])
But this will also work for 3d, 4d, ... arrays.
Upvotes: 5