3

I am trying to add each element of a numpy array in turn to another numpy 1D array, but not as an element-wise operation. More specifically, define func:

import numpy as np

array1 = np.array([1,2,3,4])
array2 = np.array([10,20,30])

def func(array1,array2):
  #what goes here?
  return output_array

output_array = func(array1,array2)

So that: output_array = np.array([[11,12,13,14],[21,22,23,24],[31,32,33,34]])

I have managed to make it work using:

def func(array1,array2):
  return np.array(list(map(lambda x: x + array1,array2)))

However, it seems like there should be a much better way to do this, and it would also be useful to generalise this to n-dimensions. I have had a try with np.vectorize():

def func(array1,array2):
  np_function = np.vectorize(lambda x: x + array1)
  return np_function(array2)

But this does not work as it tries to assign a sequence to a single array element inside the iterator (error "setting an array element with a sequence").

0

3 Answers 3

4

You don't need a special function or anything, this is a text book use case for numpy's broadcasting functionality. All you need is:

output_array = array1[None, :] + array2[:, None]  # or even array1 + array2[:, None]

To understand it take a look at the differences between

print(array1.shape)          # (4,)
print(array1[:, None].shape) # (4, 1)
print(array1[None, :].shape) # (1, 4)

When you broadcast a (4, 1) with a (1, 4) you get a (4, 4)

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

7 Comments

This is what I was looking for - would this method support N-dims without the specific indexing inside [ ]?
nD solution: def outer_add(*arrays): return reduce(np.add.outer, arrays)
Unfortunately can't add that as an answer thanks to the dupe-hammer-happy 10k user up there >.>
@DanielF np.add.outer works just fine for n-dim arrays as well, does it not? You can always draw the attention of the voter with tagging, if there are doubts on voting.
@Divakar I thought @toomuchrock wanted multiple 1d inputs -> nd output. But yeah, np.add.outer works for nd inputs as well.
|
1

Another way: np.add(array2.reshape(3,1), array1)

1 Comment

...but I like the simplicity of Dan's answer.
1

Just reshape your first array to 2d then add it to second array.

array3 = np.reshape(array2,(-1, 1))+ array1

Output :

[[11 12 13 14]
 [21 22 23 24]
 [31 32 33 34]]

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.