2

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]]

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice with the general solution; I was not aware of the slices function. So now I can make my own function def slices(arr): return tuple(slice(mi) for mi in arr.shape), and then simply do a[slices(b)] = b.
@EquipDev: yes indeed. If you need to construct such tuple multiple times, this can definitely be benificial.
4

Get the shape of array to be assigned and then slice the destination array and assign -

m,n = b.shape
a[:m,:n] = b

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.