Use the size parameter:
import numpy as np
coordinates = np.random.randint(0, 100, size=(30, 10, 2))
will produce a NumPy array with integer values between 0 and 100 and of shape (30, 10, 2).
I have a 3D Numpy array (of user-specified dimensions) of 1s and 0s (how many 1s dependant on user input). For a part of the simulation, I have to pick a random element of this array.
I have tried using numpy.random.choice and random.sample but without any success. When I had to fill the 3d array with 1s, I had trouble selecting random elements to fill with 1s. The solution I found on google was reshaping to 1D, using random.choice and then reshaping back to 3D. It worked well.
My problem now is that the element I now choose at random, I have to also obtain the index for (so that I can reassign it from a 1 to a 0 or viceversa), so reshaping won't work since I would get indices of a 1d reshaped array. Furthermore the randomly selected element has to be a 0, that is a condition I am also struggling to implement with random.choice and random.sample.
My simulation has to run sometimes in a loop of 10000 operations. I have been trying to find an easy way to do this without making the simulation less efficient, so some approaches I am thinking of doing I haven't tried yet (I have thought of picking a 2d array within my array and then pick a row/column and then pick the element, but I am scared it will make my simulation take too long to run).
Can someone help me with this task? It's driving me nuts that something as "simple" as picking an element within a 3D array is so hard to implement.
You should use a list comprehension:
>>> import pprint
>>> n = 3
>>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]
>>> pprint.pprint(distance)
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> distance[0][1]
[0, 0, 0]
>>> distance[0][1][2]
0
You could have produced a data structure with a statement that looked like the one you tried, but it would have had side effects since the inner lists are copy-by-reference:
>>> distance=[[[0]*n]*n]*n
>>> pprint.pprint(distance)
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> distance[0][0][0] = 1
>>> pprint.pprint(distance)
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]],
[[1, 0, 0], [1, 0, 0], [1, 0, 0]],
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]]
numpy.arrays are designed just for this case:
numpy.zeros((i,j,k))
will give you an array of dimensions ijk, filled with zeroes.
depending what you need it for, numpy may be the right library for your needs.