如何从两个不同数组的元素计算中 return 数组?

How to return array from element-wise calculation on two different arrays?

我有以下两个 n 个元素的 numpy 数组:

A = np.array([2 5 8 9 8 7 5 6])
B = np.array([8 9 6 5 2 8 5 7])

我要获取数组C:

C = np.array([sqrt(2^2+8^2) sqrt(5^2+9^2) ... sqrt(6^2+7^2)])

即数组C由n个元素组成;每个元素将等于 A 中相应元素的平方加上 B 中相应元素的平方的平方根。

我试过使用np.apply_along_axis,但似乎这个函数是专为一个数组设计的。

如评论中所述,您可以使用:

C = np.sqrt(A**2 + B**2)

或者您可以使用 comprehensionzip:

C = [sqrt(a**2 + b**2) for a, b in zip(A,B)]

如果您的数组很大,请考虑使用 np.square 而不是 ** 运算符。

In [16]: np.sqrt(np.square(A) + np.square(B))
Out[16]: 
array([  8.24621125,  10.29563014,  10.        ,  10.29563014,
         8.24621125,  10.63014581,   7.07106781,   9.21954446])

虽然执行时间的差异非常小。

In [13]: ar = np.arange(100000)

In [14]: %timeit np.square(ar)
10000 loops, best of 3: 158 µs per loop

In [15]: %timeit ar**2
10000 loops, best of 3: 179 µs per loop