Tomergt45
Tomergt45

Reputation: 679

How can you fill a NumPy array with another array (possibly with different shape)

Not sure how to ask my question, maybe the title doesn't reflect my question correctly, and if that is the case feel free to correct me.

I have two arrays

a = np.zeros((2, 2))
b = np.ones((3, 3))

I want a func that would yield the following result:

c = func(a, b)
print(c)

# array([[1., 1.],
#       [1., 1.]])

But if we switch position of a and b when we pass them to the function, we will get the following result:

c = func(b, a) # Note the change
print(c)

# array([[0., 0., 1.],
#       [0., 0., 1.],
#       [1., 1., 1.]])

Edit: for clarification, here is another example to answer @mercury's question.

a = np.zeros((2, 3))
b = np.ones((3, 2))

c = func(a, b)
print(c)

# array([[1., 1., 0.],
#       [1., 1., 0.]])

Upvotes: 1

Views: 872

Answers (1)

Tomergt45
Tomergt45

Reputation: 679

I think I found an answer, not sure about it tho.

def func(a, b):
    x1, x2 = np.min((a.shape, b.shape), 0)
    c = a.copy()
    c[:x1, :x2] = b[:x1, :x2]
    return c

I'll be happy if someone who understands the question could reply if this actually solves it, and if so, how should this operation be called?

Upvotes: 1

Related Questions