I want to modify the matrix created in arr per column (the one that the user wants) and per row (the one that the user wants) entering the value he wants:
from numpy import *
arr = zeros((2,2))
for j in arr:
for k in j:
k = 5
print arr
I want to modify the matrix created in arr per column (the one that the user wants) and per row (the one that the user wants) entering the value he wants:
from numpy import *
arr = zeros((2,2))
for j in arr:
for k in j:
k = 5
print arr
from numpy import *
arr = zeros((2,2))
for j in range(len(arr)):
for k in range(len(arr[j])):
arr[j][k] = 5
print(arr)
The operation of range(n)
is generates a list of n
(1, 2, 3, etc) values to be able to iterate over it.
With len(objeto)
you get the size of the list or chain.
for j in range(len(arr)):
Generate the size list equal to that of arr (2) and iterate over it.
j
equals the current position in the list.
for k in range(len(arr[j])):
Get the size of the list that is inside
from the first list len(arr[j])
and iterates again in it.
k
equals the current position in the list.
arr[j][k] = 5
Then we access the first list arr[j]
and then we have to go through the
for the value that is in the second list that is within the first arr[j][k]
Direct allocation within for-in
does not work in Python or in NumPy. You need to use indexes to do that:
import numpy as np
arr = np.zeros((2,2))
for j in np.arange(arr.shape[0]):
for k in np.arange(arr.shape[1]):
arr[j, k] = 5
Another option is to use np.ndenumerate
:
import numpy as np
arr = np.zeros((2,2))
for (i, j), valor in np.ndenumerate(arr):
arr[i, j] = 5
Since you are using NumPy, you should use their methods ( narange
, array.shape
, etc) preferably for efficiency and simplification of the code itself.
If you wanted to change all the values of the array at the same time by a number entered by the user then you would not need any cycle:
>>> import numpy as np
>>> arr = np.zeros((2,2))
>>> arr.fill(5)
>>> print(arr)
[[ 5. 5.]
[ 5. 5.]]
Do not use from módulo import *
as a way to import into Python, that is dangerous and a bad practice since you can end up overwriting functions / methods of the module without realizing it leading to unexpected and difficult to track errors (even more in complex libraries and extensive as NumPy, Pandas, SciPy, etc). Use any of these formulas instead: import numpy
, import numpy as np
or from numpy import zeros, arange...
.