Skip to main content
 首页 » 编程设计

python之在两个向量上广播函数以获得二维 numpy 数组

2025年05月04日10shihaiming

我想在一个向量上广播一个函数 f,这样结果就是一个矩阵 P,其中 P[i,j] = f(v[i], v[j])。 我知道我可以简单地做到这一点:

P = zeros( (v.shape[0], v.shape[0]) ) 
for i in range(P.shape[0]): 
    for j in range(P.shape[0]): 
        P[i, j] = f(v[i,:], v[j,:]) 

或更 hacky:

from scipy.spatial.distance import cdist 
P = cdist(v, v, metric=f)  

但我正在寻找最快、最简洁的方法。 这似乎是 numpy 应该内置的广播功能。 有什么建议吗?

请您参考如下方法:

我相信你搜索的是numpy.vectorize .像这样使用它:

def f(x, y): 
    return x + y 
v = numpy.array([1,2,3]) 
# vectorize the function 
vf = numpy.vectorize(f) 
# "transposing" the vector by producing a view with another shape 
vt = v.reshape((v.shape[0], 1) 
# calculate over all combinations using broadcast 
vf(v, vt) 
 
Output: 
array([[ 2.,  3.,  4.], 
       [ 3.,  4.,  5.], 
       [ 4.,  5.,  6.]])