I would like to create a 2D array using nested loop. What is the problem with this code?
import numpy
b = np.array([])
for i in range(2):
for j in range(5):
b[i][j]=i+j
print(b)
I would like to create a 2D array using nested loop. What is the problem with this code?
import numpy
b = np.array([])
for i in range(2):
for j in range(5):
b[i][j]=i+j
print(b)
The numpy array you are defining is not the right shape for the loop you are using. b = np.array([]) gives you an array of shape (0,)
You can use something like np.zeros to define your 2D array.
import numpy as np
b = np.zeros((3,6))
for i in range(2):
for j in range(5):
b[i][j]=i+j
print(b)
The output will be
[[0. 1. 2. 3. 4. 0.]
[1. 2. 3. 4. 5. 0.]
[0. 0. 0. 0. 0. 0.]]
Another option is to make a 2D list, fill it up in for loops, and convert to numpy array later
import numpy as np
#2D array
b = [ [0 for _ in range(6)] for _ in range(3)]
#Fill up array with for loops
for i in range(2):
for j in range(5):
b[i][j]=i+j
#Convert to numpy array
print(np.array(b))
The output will be
[[0 1 2 3 4 0]
[1 2 3 4 5 0]
[0 0 0 0 0 0]]
the Proper way to do this is by following these four steps:
1 Initialize an empty array to store the results in
2 Create a for-loop looping over the lines/columns of the data array Inside the loop:
3 Do the computation
4 Append the result array
This is just a random initialization trick with for loop for 3D.
import numpy as np
np.random.seed(0) # seed
x1 = np.random.randint(10, size=3) # One-dimensional array
x2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array
x3 = np.random.randint(10, size=(3, 4, 5)) # Three-dimensional array
Later on you may use your magic for looping magic.
for _ in range(2):
for __ in range(4):
for ___ in range(5):
x3[_][__][___]=_+__+___