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?

H.Choi
  • 3,095
  • 7
  • 26
  • 24

2 Answers2

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]])
yatu
  • 86,083
  • 12
  • 84
  • 139
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/

abdoulsn
  • 842
  • 2
  • 16
  • 32