6

I have two numpy arrays

A= array([[1,2,3,4],
          [5,6,7,8],
          [9,10,11,12]])

B = array([10,20,30])

and I want to generate array C:

C = array([11,12,13,14],
          [25,26,27,28],
          [39,40,41,42]])

I have tried some ways.. but they seem very inefficient. Is there any way this can be done efficiently?

1
  • isnt it just addition of 2 array ? i mean C = A+B(T) (but with each column of A) and what did you tried? Commented Mar 26, 2019 at 10:31

2 Answers 2

6

This can be done with a little help from broadcasting by adding a new axis to B (either with None or with np.newaxis) so that they have compatible shapes, and B is broadcastable accross the larger array A:

A + B[:,None]

array([[11, 12, 13, 14],
       [25, 26, 27, 28],
       [39, 40, 41, 42]])
Sign up to request clarification or add additional context in comments.

Comments

1

pleas look at this example :

    ethernet_devices = [1, [7], [2], [8374163], [84302738]]
    usb_devices = [1, [7], [1], [2314567], [0]]

    all_devices = [x + y for x, y in zip(ethernet_devices, usb_devices)]

Sources: https://therenegadecoder.com/code/how-to-sum-elements-of-two-lists-in-python/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.