简体   繁体   English

如何使用numpy有效地从每列中减去值

[英]How to efficiently subtract values from each column with numpy

I have a 2D array of shape (50,50). 我有一个2D阵列形状(50,50)。 I need to subtract a value from each column of this array skipping the first), which is calculated based on the index of the column. 我需要从跳过第一个的数组的每一列中减去一个值,这是根据列的索引计算的。 For example, using a for loop it would look something like this: 例如,使用for循环它看起来像这样:

for idx in range(1, A[0, :].shape[0]):
    A[0, idx] -= idx * (...) # simple calculations with idx 

Now, of course this works fine, but it's very slow and performance is critical for my application. 现在,当然这很好用,但它非常慢,性能对我的应用程序至关重要。 I've tried computing the values to be subtracted using np.fromfunction() and then subtracting it from the original array, but results are different than those obtained by the for loop iteractive subtraction: 我已经尝试使用np.fromfunction()计算要减去的值,然后从原始数组中减去它,但结果与for循环迭代减法获得的结果不同:

 func = lambda i, j: j * (...) #some simple calculations
 subtraction_matrix = np.fromfunction(np.vectorize(func), (1,50))

 A[0, 1:] -= subtraction_matrix

What am I doing wrong? 我究竟做错了什么? Or is there some other method that would be better? 或者还有其他方法会更好吗? Any help is appreciated! 任何帮助表示赞赏!

All your code snippets indicate that you require the subtraction to happen only in the first row of A (though you've not explicitly mentioned that). 所有代码片段都表明您要求减法发生A的第一行 (尽管您没有明确提到过)。 So, I'm proceeding with that understanding. 所以,我正在进行这种理解。

Referring to your use of from_function() , you can use the subtraction_matrix as below: 参考你对from_function()使用,你可以使用subtraction_matrix ,如下所示:

A[0,1:] -= subtraction_matrix[1:]

Testing it out (assuming shape (5,5) instead of (50,50) ): 测试它(假设形状(5,5)而不是(50,50) ):

import numpy as np

A = np.arange(25).reshape(5,5)
print (A)

func = lambda j: j * 10 #some simple calculations
subtraction_matrix = np.fromfunction(np.vectorize(func), (5,), dtype=A.dtype)

A[0,1:] -= subtraction_matrix[1:]
print (A)

Output: 输出:

[[ 0  1  2  3  4]        # print(A), before subtraction
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

[[  0  -9 -18 -27 -36]   # print(A), after subtraction
 [  5   6   7   8   9]
 [ 10  11  12  13  14]
 [ 15  16  17  18  19]
 [ 20  21  22  23  24]]

If you want the subtraction to happen in all the rows of A , you just need to use the line A[:,1:] -= subtraction_matrix[1:] , instead of the line A[0,1:] -= subtraction_matrix[1:] 如果你想在A 所有行中发生减法,你只需要使用线A[:,1:] -= subtraction_matrix[1:] ,而不是线A[0,1:] -= subtraction_matrix[1:]

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

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