4

What is an efficient numpy way of achieving an array of results based on a pair of index datasets?

So, lets say there are 2 arrays these are the row and column headers in the table underneath:

a = [1,3,4,6]
b = [2,7,8,10,15]

The resultant matrix I am looking for is a function based on a and b: f(a,b) So assuming the function is simply a+b thus:

  a ||  1 |  3 |  4 |  6
=========================
b 2 ||  3 |  5 |  6 |  8 <-- ie 2+1=3, 2+3=5 etc 
  7 ||  8 | 10 | 11 | 13
  8 ||  9 | 11 | 12 | 14
 10 || 11 | 13 | 14 | 16
 15 || 16 | 18 | 19 | 21

Obviously I could loop through each array and update the results of say a np.zeros() but I am assuming there should be a more efficient way of achieving this? TIA

3 Answers 3

6

You can do this efficiently and vectorized in NumPy using broadcasting.

import numpy as np
a = np.array([1, 3, 4, 6])
b = np.array([2, 7, 8, 10, 15])
result = b[:, None] + a
print(result)
Sign up to request clarification or add additional context in comments.

Comments

4

Another possible solution:

np.add.outer(b, a)

The np.add function performs element-wise addition, and the outer method applies that operation to every possible combination of one element from each input array. We can use other function beyond add.

Output:

array([[ 3,  5,  6,  8],
       [ 8, 10, 11, 13],
       [ 9, 11, 12, 14],
       [11, 13, 14, 16],
       [16, 18, 19, 21]])

1 Comment

One of the advantages of this approach is that you can provide the dtype or out parameter to .outer
0

I did not understand why numpy was mentioned. Regular Python iterables will be enough for your goal.

a = [1,3,4,6]
b = [2,7,8,10,15]

def f(a, b): return a + b
# or
# f = lambda a, b: a + b

[[f(a, b) for a in a] for b in b]
[[ 3,  5,  6,  8],
 [ 8, 10, 11, 13],
 [ 9, 11, 12, 14],
 [11, 13, 14, 16],
 [16, 18, 19, 21]]

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.