简体   繁体   English

将操作应用于python中二维numpy数组的每个向量

[英]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.如果我有两个 numpy 2DArrays 让我们说 A 和 B 以及一个函数 f 它接受 2 个向量并输出一个标量。 Performance is important and numpy array operations are really fast so how do I get the matrix:性能很重要,并且 numpy 数组操作非常快,所以我如何获得矩阵:

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

a(i) and b(i) being 1d arrays/vectors a(i) 和 b(i) 是一维数组/向量

By applying something like f(A,B) and without using any loops.通过应用类似 f(A,B) 的东西而不使用任何循环。

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?使用某些方法我可以使用 axis=1 但我如何定义我自己的函数或者有其他方法?

The easiest, and most efficient, solution is to use a for loop.最简单、最有效的解决方案是使用 for 循环。 np.vectorize won't help you here, because it passes scalars to a function. np.vectorize 在这里对您没有帮助,因为它将标量传递给函数。

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.将打印您想要返回的 f 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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