Issue
I was trying to modify a numpy
array after construction using the code below. (yes, I know there are functions to do that like np.random.randint(100, size=(2,3))
). It looks like there's no problem of reading using the Python style syntax, but I cannot make changes to the ndarray.
Is this a possible bug? Or should we call it a feature like most developers would do?
import random
import numpy as np
def print_data(arr):
for row in arr:
for col in row:
print(f'{col}\t', end=' ')
print()
# Both creation methods have the same bug
##a = np.ndarray(shape=(2,3),dtype=int)
a = np.zeros((2,3), dtype=int)
print_data(a)
print()
for row in a:
for cell in row:
# cell was printed out
cell = random.randrange(99)
print(cell, end=' ')
# row was not changed
print(row)
print()
print_data(a)
print()
for row in a:
for i in range(len(row)):
row[i] = random.randrange(99)
print(row[i], end=' ')
print(row)
print()
print_data(a)
The output:
1 0 -447458960
32763 -447580336 32763
6 2 77 [ 1 0 -447458960]
50 20 75 [ 32763 -447580336 32763]
1 0 -447458960
32763 -447580336 32763
95 61 3 [95 61 3]
76 23 82 [76 23 82]
95 61 3
76 23 82
As suggested by the output, the first double loop prints out the random number without any problem. However, the matrix element was not modified. In the second code block, the a[i]
worked. I also tested that it worked if a[i,j]
was used in a double loop.
Any idea or a link to some detailed explanation would be appreciated.
Solution
It's working as intended:
To change a single cell in a 2D numpy array, use
a[i,j] = ...
. This is an item assignment, which for numpy arrays changes a single cell within the array object.cell = ...
only changes the variablecell
. Think of a variable as a reference to an object; a variable assingment such ascell = ...
andfor cell in ...:
makes the variable refer to a different object.
Answered By - pts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.