Is there a way to modify a numpy array inside a loop column by column?
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]]
?
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?
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:
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