Reputation: 1
I have been trying to get a personal homework to work properly but I can't seem to get it right. I need to insert a random value into a 2D array using two For cycles and print the array. This is what I have but it's not finished and it's the barebones of my struggle.
import numpy as np
import random
arr = np.array([], [])
for i in range(0, 6):
for j in range(0, 6):
value = random.randint(0, 6)
arr[i][j] = value
print(arr(i, j))
print('')
I want to know how to insert the random value into the array's position, like if the for cycle is telling me I'm at the position 0,0 , then I want to insert a number into that position.
Upvotes: 0
Views: 3490
Reputation: 405715
Creating an array with arr = np.array([], [])
gives you an array with no rows and no columns, so you'll be using indexes that are out of bounds as soon as you try to set a value. You need to give some dimension to the array when you create it, even if you don't provided initial values. There are several ways to do that, but try this:
import numpy as np
import random
arr = np.empty(shape=(6, 6)) # np.zeroes would also work
print(arr)
for i in range(0, 6):
for j in range(0, 6):
value = random.randint(0, 6)
arr[i][j] = value
print(arr)
Upvotes: 0
Reputation: 92440
In general, you should do everything you can to avoid loops with Numpy. It defeats the purpose. For almost anything you want to do, there is a Numpy way that doesn't require a loop.
Here you can use numpy.random.randint
and built the array directly without the loop. This will be much faster:
import numpy as np
# arguments are low, high, shape
arr = np.random.randint(0, 6, (6, 6))
# array([[0, 4, 0, 5, 3, 4],
# [2, 2, 0, 0, 3, 1],
# [1, 3, 5, 0, 4, 2],
# [3, 1, 1, 4, 5, 2],
# [2, 5, 4, 3, 2, 3],
# [2, 3, 0, 2, 0, 0]])
Upvotes: 2
Reputation: 1658
Some changes:
print(arr(i, j))
To print(arr[i, j])
arr = np.zeros((6, 6))
import random
for i in range(0, 6):
for j in range(0, 6):
value = random.randint(0, 6)
arr[i][j] = value
print(arr[i, j])
If you want to print the entire array, you can do this:
arr = np.zeros((6, 6))
import random
for i in range(0, 6):
for j in range(0, 6):
value = random.randint(0, 6)
arr[i][j] = value
print(arr)
Upvotes: 0