15

I am generating a 2D array of random integers using numpy:

import numpy
arr = numpy.random.randint(16, size = (4, 4))

This is just an example. The array I am generating is actually enormous and of variable size. Since the numbers are always going to be from 0 to 16, I would like to save some space and have the array be of type uint8. I have tried the following

arr = numpy.random.randint(16, size = (width, height), dtype = numpy.uint8)

in an attempt to match the behavior of zeros and ones, but I get the following error:

Traceback (most recent call last):

File "<ipython-input-103-966a510df1e7>", line 1, in <module>
    maze = numpy.random.randint(16, size = (width, height), dtype = numpy.uint8)

  File "mtrand.pyx", line 875, in mtrand.RandomState.randint (numpy/random/mtrand/mtrand.c:9436)

TypeError: randint() got an unexpected keyword argument 'dtype'

The docs for randint() do not mention anything about being able to set the type. How do I create a random array with a specific integer type? I am not tied to any one function, just a uniform distribution from 0 to 16 of type uint8.

2
  • 1
    As of NumPy 1.11 randint now has this missing dtype= option. Commented Dec 27, 2017 at 10:35
  • @Hannes. Thanks. I can no longer delete the question, so if you were to post an answer, I'd accept it. Commented Dec 27, 2017 at 15:15

2 Answers 2

16

The quickest way is to use the astype() method:

x = np.random.randint(16, size=(4,4)).astype('uint8')

This works on any numpy array. But please note that by default it does not check that the casting is valid.

Sign up to request clarification or add additional context in comments.

Comments

9

The issue is that np.random.randint cannot specify dtype

import numpy as np

random_array = np.random.randint(0,16,(4,4))

[[13 13  9 12]
 [ 4  7  2 11]
 [13  3  5  1]
 [ 9 10  8 15]]

print(random_array.dtype)

>>int32

random_array = np.array(random_array,dtype=np.uint8)

print(random_array.dtype)

>>uint8

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.