Python 给定两个大小相同的numpy数组,如何将函数应用于两个位于相同位置的每对元素?
我有两个大小相同的numpy数组,希望对位于同一位置的每对元素应用一个函数(这里是Python 给定两个大小相同的numpy数组,如何将函数应用于两个位于相同位置的每对元素?,python,numpy,multidimensional-array,Python,Numpy,Multidimensional Array,我有两个大小相同的numpy数组,希望对位于同一位置的每对元素应用一个函数(这里是binom\u test) 下面的代码符合我的要求,但我想存在一个更优雅的解决方案 import numpy as np from scipy.stats import binom_test h, w = 3, 4 x=np.random.random_integers(4,9,(h,w)) y=np.random.random_integers(4,9,(h,w)) result = np.ones((h,w
binom\u test
)
下面的代码符合我的要求,但我想存在一个更优雅的解决方案
import numpy as np
from scipy.stats import binom_test
h, w = 3, 4
x=np.random.random_integers(4,9,(h,w))
y=np.random.random_integers(4,9,(h,w))
result = np.ones((h,w))
for row in range(h):
result[row,:] = np.array([binom_test(x[row,_], x[row,_]+y[row,_]) for _ in range(w)])
print(result)
第一个参数可以是数组,但第二个参数
stats.binom_test的参数必须是整数,而不是数组
因此,除非x+y
(作为第二个参数传递的值)包含大量
重复这些值,无法减少对stats.binom\u test
的调用次数。
通常,您只需为x
和x+y
中的每个元素调用一次
但是,NumPy确实有一个helper函数,它可以使语法更漂亮np.vectorize
返回一个函数,该函数可以将数组作为输入并返回数组作为输出<代码>np。矢量化主要是。在引擎盖下,它执行for循环
,与您编写的循环非常相似。因此,循环的显式可以替换为
binom_test = np.vectorize(stats.binom_test)
result = binom_test(x, x+y)
屈服
[[ 1. 0.75390625 0.77441406 0.60723877]
[ 1. 0.79052734 0.77441406 0.77441406]
[ 1. 1. 1. 1. ]]
为什么不能同时循环两个阵列?
[[ 1. 0.75390625 0.77441406 0.60723877]
[ 1. 0.79052734 0.77441406 0.77441406]
[ 1. 1. 1. 1. ]]