1

I have a set of 2D arrays that I wish to add up but they are of different lengths. I want it to add up such that they are centered on top of each other. For example for 1D:

    a = [1,1,1,1,1]
    b = [2,2,2]

therefore: c = [1,3,3,3,1]

I'm not sure how to approach this using numpy?

3
  • 2
    What do you mean by add up? I would think c is [1, 3, 3, 3, 1] if you're actually adding them. Can you clarify? Commented Jul 17, 2020 at 8:03
  • What if one of the inputs is even size and the other is odd size in some dimension? And what exactly do you hope to accomplish by doing this? Commented Jul 17, 2020 at 8:06
  • Sorry thats what i meant and I'm trying to sum up images Commented Jul 17, 2020 at 8:15

2 Answers 2

2

Assuming that for your add up operation 0 is neutral element, for centering part you might harness numpy.pad in constant mode, as long as all dimension are odd. Consider following example, lets say we have (3,5)-shaped array and we want to obtain (11,9)-shaped array then we might do:

import numpy as np
a = np.ones((3,5),dtype=int)
a_h, a_w = a.shape
required_h = 11
required_w = 9
vert_pad_size = (required_h - a_h)//2
hor_pad_size = (required_w - a_w)//2
centered = np.pad(a, [(vert_pad_size,vert_pad_size),(hor_pad_size,hor_pad_size)], mode='constant')
print(centered)

Output:

[[0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 1 1 1 1 1 0 0]
 [0 0 1 1 1 1 1 0 0]
 [0 0 1 1 1 1 1 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]]

Explanation: I first calculate how many rows/columns must be added to up, bottom,left,right to get desired shape and then do it using pad. Keep in mind that this solution assumes all dimension of original array and desired array are odd.

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

Comments

-1

In general, you could assign slices:

>>> import numpy as np
>>> A = np.ones((5,5))
>>> B = np.zeros((3,3))
>>> A
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])
>>> B
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
>>> A[1:-1, 1:-1] = B
>>> A
array([[1., 1., 1., 1., 1.],
       [1., 0., 0., 0., 1.],
       [1., 0., 0., 0., 1.],
       [1., 0., 0., 0., 1.],
       [1., 1., 1., 1., 1.]])

Calculating the indices for the slice is left as an exercise.

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.