Before you flag this as duplicate, let me explain to you that I read this page and many others and I still haven't found a solution to my problem.
This is the problem I'm having: given two 2D arrays, I want to apply a function F over the two arrays. F takes as input two 1D arrays.
import numpy as np
a = np.arange(15).reshape([3,5])
b = np.arange(30, step=2).reshape([3,5])
# what is the 'numpy' equivalent of the following?
np.array([np.dot(x,y) for x,y in zip(a,b)])
Please note that np.dot
is just for demonstration. The real question here is any generic function F that works over two sets of 1D arrays.
- vectorizing either fails outright with an error or it applies the function element-by-element, instead of array-by-array (or row-by-row)
np.apply_along_axis
applies the function iteratively; for example, using the variables defined above, it doesF(a[0], b[0])
and combines this withF(a[0], b[1])
andF(a[0], b[2])
. This is not what I'm looking for. Ideally, I would want it to stop at justF(a[0], b[0])
- index slicing / advanced slicing doesn't do what I would like either. For one, if I do something like
np.dot(a[np.arange(3)], b[np.arange(3)])
this throws a ValueError saying that shapes (3,5) and (3,5) are not aligned. I don't know how to fix this.
I tried to solve this in any way I could, but the only solution I've come up with that works is using list comprehension. But I'm worried about the cost to performance as a result of using list comprehension. I would like to achieve the same effect using a numpy operation, if possible. How do I do this?