2

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?

3
  • Are you aware of numpy's array slicing syntax? docs.scipy.org/doc/numpy/reference/… Commented Jul 11, 2013 at 12:26
  • You say matrix, but your code says ndarray? Those are two different things Commented Jul 11, 2013 at 12:53
  • Thanks. I've corrected and extended my question. Commented Jul 11, 2013 at 12:58

1 Answer 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:

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
Sign up to request clarification or add additional context in comments.

3 Comments

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 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".
Tested... It works and completely answers my question! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.