1

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)
1
  • 1
    you should accept the answer if the problem is gone @Reza Commented May 6, 2019 at 10:11

4 Answers 4

6

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

1 Comment

Great! Glad to help @Reza Please consider accepting the answer if it helped you :) stackoverflow.com/help/someone-answers
1

I understand you asked how to do this with nested loops, so apologies if you don't find this useful. I'd just thought I'd share how I normally do this:

b = np.arange(10).reshape(2,5)
print(b)
[[0 1 2 3 4]
 [5 6 7 8 9]]

Comments

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

1 Comment

Except with numpy arrays, this may be costly as numpy arrays are immutable for the most part. I.e. appending the result into the array will create a new copy; and for this copy to persist, it needs to be assigned. Potentially, a lot of arrays will be created and thrown away. Nevertheless, your answer isn't entirely wrong.
0

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[_][__][___]=_+__+___

Comments

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.