如何在Python中为numpy矩阵编写函数

时间:2015-05-19 12:01:06

标签: python numpy matrix

我有一个numpy矩阵A,我需要一个函数来计算(A [i,j] /第i列中所有元素的总和) - A [i,j] / j-中所有元素的总和排 它适用于A中的每个元素。

我已经尝试过写下以下内容:

a = A.sum(axis=0) 
b = A.sum(axis=1) 

for i in A: 
    for j in i: 
        f = A[i,j]/a(i) - A[i,j]/b(j)

2 个答案:

答案 0 :(得分:2)

您应该寻找一个矢量化解决方案,而不是循环遍历所有元素

A/A.sum(axis=0)[np.newaxis,:] -  A/A.sum(axis=1)[:,np.newaxis]

假设

In [35]: A = np.random.rand(10,3)
Out[35]:
array([[ 0.26070074,  0.58940996,  0.78665012],
       [ 0.7420538 ,  0.72214655,  0.66633183],
       [ 0.67189673,  0.67298124,  0.04628626],
       [ 0.93935375,  0.45030544,  0.38292913],
       [ 0.45410731,  0.26557299,  0.09573014],
       [ 0.99872912,  0.31092656,  0.46294278],
       [ 0.61108329,  0.71140089,  0.85548017],
       [ 0.80012964,  0.64749927,  0.3292407 ],
       [ 0.33229818,  0.01810878,  0.44460486],
       [ 0.86525557,  0.0569463 ,  0.43183502]])

您可以执行以下操作。

In [36]: A*(1/A.sum(axis=0)[np.newaxis,:] -  1/A.sum(axis=1)[:,np.newaxis])
Out[36]:
array([[-0.12022572, -0.22751579, -0.3058817 ],
       [-0.23713606, -0.17649948, -0.16474676],
       [-0.3823249 , -0.33236228, -0.0229904 ],
       [-0.38921906, -0.1527391 , -0.13097127],
       [-0.48888156, -0.26594996, -0.09613741],
       [-0.41381789, -0.10546217, -0.15833642],
       [-0.18903571, -0.16660122, -0.20276794],
       [-0.33044427, -0.21874513, -0.11216096],
       [-0.36820095, -0.01870431, -0.46048657],
       [-0.5094047 , -0.02924623, -0.22300407]])

答案 1 :(得分:0)

我希望这可以提供帮助:

def f(i,j,A):
    return A[i,j] * ( 1. / np.sum(A[i,])  ) -  ( 1. / np.sum(A[:,j])  )