0

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.

1
  • Show a complete traceback for any errors you get Commented Sep 4, 2021 at 17:38

3 Answers 3

2

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

Comments

0

Some changes:

  1. Define the array with np.zeros
  2. 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)

Comments

0

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)

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.