Reza
Reza

Reputation: 33

Create 2D numpy array through nested loop

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)

Upvotes: 1

Views: 8725

Answers (4)

prosti
prosti

Reputation: 46301

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

Upvotes: 0

maxioatic
maxioatic

Reputation: 136

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]]

Upvotes: 1

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

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]]

Upvotes: 6

Avinash Koshal
Avinash Koshal

Reputation: 85

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

Upvotes: 0

Related Questions