简体   繁体   中英

Modify NumPy array in loops

I have a problem with array manipulation in NumPy. If I create two arrays x and y , and do

x = x - y 

I get what I expect, that is each element of y is subtracted from the corresponding element of x , and thus x is modified. However, if I put this in a loop:

m = np.array([[1,2,3],[1,2,3]])
y = array([1, 1, 1])
for i in m:
    i = i - y

the matrix m remains unaltered. I am sure I am missing something very basic... How can I change the array m in a loop?

This is not related with numpy matrix, but how python deal with your

i = i - y

i - y produces a new reference of an array. When you assigns it to name i, so i is not referred to the one it was before, but the newly created array.

The following code will meet your purpose

for idx, i in enumerate(m):
    m[idx] = i - y

Update: I realize that the easiest thing is to do

m = m-y

This does directly what I expected!

If working with an example where you are unable to avoid looping through the array but still want to change the row, do this

m = np.array([[1,2,3],[1,2,3]])
y = array([1, 1, 1])
for i in m:
    i -= y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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