Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
Are you aware of numpy's array slicing syntax? docs.scipy.org/doc/numpy/reference/… –  DaveP Jul 11 '13 at 12:26
    
You say matrix, but your code says ndarray? Those are two different things –  usethedeathstar Jul 11 '13 at 12:53
    
Thanks. I've corrected and extended my question. –  Apogentus Jul 11 '13 at 12:58

1 Answer 1

up vote 2 down vote accepted

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
share|improve this answer
    
Thanks, Jaime. Of course, I could use broadcasting for this simple task, but in my initial task I need to do more complex operation on column. What I actually need is to know the syntax how to modify array mnX by modifying it column by column in place without using column indices. Your example leaves mnX unchanged. –  Apogentus Jul 11 '13 at 14:42
    
@Apogentus Jaime's example does modify mnX: col is a view of mnX, and modifying it inplace (+=) changes mnX. In fact, it's precisely "modify[ing] array mnX by modifying it column by column in place without using column indices". –  jorgeca Jul 11 '13 at 15:07
    
Tested... It works and completely answers my question! Thank you! –  Apogentus Jul 17 '13 at 12:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.