简体   繁体   中英

Applying an operation to each vector from 2d numpy arrays in python

I need it for 2d arrays but would also be interested in higher dimensions. If I have two numpy 2DArrays lets say A and B and a function f which takes 2 vectors and puts out a scalar. Performance is important and numpy array operations are really fast so how do I get the matrix:

(f(a1,b1),f(a1, b2)...)
(f(a2,b1), f(a2,b2)...)
(...                  )

a(i) and b(i) being 1d arrays/vectors

By applying something like f(A,B) and without using any loops.

With some methods I can use the axis=1 but how do I define my own function like that or is there an other way?

The easiest, and most efficient, solution is to use a for loop. np.vectorize won't help you here, because it passes scalars to a function.

Assuming your arrays have two columns:

for a,b in zip(A,B):
    print(f(a[0],b[0]))
    print(f(a[1],b[1]))

would print the values of f that you would want to return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM