Is there a way to modify a numpy array inside a loop column by column?
是否有一种方法可以通过列修改一个循环列中的numpy数组?
I expect this could be done by some code like that:
我希望可以通过这样的代码来完成:
import numpy as n
cnA=n.array([[10,20]]).T
mnX=n.array([[1,2],[3,4]])
for cnX in n.nditer(mnX.T, <some params>):
cnX = cnX+cnA
Which parameters should I use to obtain mnX=[[10,23],[12,24]]
?
我应该使用哪些参数来获取mnX=[10,23],[12,24] ?
I am aware that the problem could be solved using the following code:
我知道这个问题可以用下面的代码来解决:
cnA=n.array([10,20])
mnX=n.array([[1,2],[3,4]])
for col in range(mnX.shape[1]):
mnX[:,col] = mnX[:,col]+cnA
Hovewer, in python we loop through modified objects, not indexes, so the question is - is it possible to loop through columns (that need to be modified in-place) directly?
Hovewer,在python中,我们是通过修改过的对象来循环的,而不是索引,所以问题是——是否可能直接循环遍历列(需要就地修改)?
1 个解决方案
#1
4
Just so you know, some of us, in Python, do iterate over indices and not modified objects when it is helpful. Although in NumPy, as a general rule, we don't explicitly iterate unless there is no other way out: for your problem, the simplest approach would be to skip the iteration and rely on broadcasting:
你知道,我们中的一些人,在Python中,在有帮助的时候迭代索引,而不是修改对象。虽然在NumPy中,作为一般规则,我们没有明确地迭代,除非没有其他解决方法:对于您的问题,最简单的方法是跳过迭代并依赖于广播:
mnX += cnA
If you insist on iterating, I think the simplest would be to iterate over the transposed array:
如果您坚持迭代,我认为最简单的方法是遍历转置数组:
for col in mnX.T:
col += cnA[:, 0].T
#1
4
Just so you know, some of us, in Python, do iterate over indices and not modified objects when it is helpful. Although in NumPy, as a general rule, we don't explicitly iterate unless there is no other way out: for your problem, the simplest approach would be to skip the iteration and rely on broadcasting:
你知道,我们中的一些人,在Python中,在有帮助的时候迭代索引,而不是修改对象。虽然在NumPy中,作为一般规则,我们没有明确地迭代,除非没有其他解决方法:对于您的问题,最简单的方法是跳过迭代并依赖于广播:
mnX += cnA
If you insist on iterating, I think the simplest would be to iterate over the transposed array:
如果您坚持迭代,我认为最简单的方法是遍历转置数组:
for col in mnX.T:
col += cnA[:, 0].T