0
0
NumpyHow-ToBeginner ยท 3 min read

How to Create Random Arrays with NumPy in Python

Use numpy.random.rand() to create an array of random floats between 0 and 1, or numpy.random.randint() for random integers within a range. Specify the shape as arguments to get arrays of any size.
๐Ÿ“

Syntax

NumPy provides several functions to create random arrays:

  • numpy.random.rand(d0, d1, ..., dn): Creates an array of given shape with random floats in [0, 1).
  • numpy.random.randint(low, high=None, size=None): Creates an array of random integers from low (inclusive) to high (exclusive).

Here, d0, d1, ..., dn define the shape of the array, and size is the shape tuple for the output array.

python
import numpy as np

# Random floats array of shape (3, 2)
np.random.rand(3, 2)

# Random integers array of shape (4,) from 0 to 9
np.random.randint(0, 10, size=4)
๐Ÿ’ป

Example

This example shows how to create a 3x3 array of random floats and a 1D array of 5 random integers between 10 and 20.

python
import numpy as np

# 3x3 array of random floats between 0 and 1
random_floats = np.random.rand(3, 3)

# 1D array of 5 random integers between 10 (inclusive) and 20 (exclusive)
random_ints = np.random.randint(10, 20, size=5)

print("Random floats array:\n", random_floats)
print("Random integers array:\n", random_ints)
Output
Random floats array: [[0.5488135 0.71518937 0.60276338] [0.54488318 0.4236548 0.64589411] [0.43758721 0.891773 0.96366276]] Random integers array: [13 19 10 14 17]
โš ๏ธ

Common Pitfalls

Common mistakes when creating random arrays include:

  • Using randint without specifying high when you want a range (it defaults to None, which causes an error).
  • Confusing the shape arguments for rand (positional shape) and randint (size keyword argument).
  • Expecting rand to generate integers (it generates floats).
python
import numpy as np

# Wrong: missing 'high' argument causes error
# np.random.randint(5, size=3)  # This works, low=0, high=5

# Correct usage:
random_ints_correct = np.random.randint(0, 5, size=3)
print(random_ints_correct)
Output
[3 1 4]
๐Ÿ“Š

Quick Reference

FunctionDescriptionExample Usage
numpy.random.randRandom floats in [0,1), shape as argumentsnp.random.rand(2,3)
numpy.random.randintRandom integers in [low, high), size as shapenp.random.randint(0, 10, size=5)
numpy.random.randnRandom floats from standard normal distributionnp.random.randn(4)
โœ…

Key Takeaways

Use np.random.rand() to create arrays of random floats between 0 and 1 with specified shape.
Use np.random.randint(low, high, size) to create arrays of random integers within a range.
Always specify the shape correctly: positional args for rand(), size= for randint().
rand() generates floats, randint() generates integers; don't confuse them.
Check arguments carefully to avoid errors like missing 'high' in randint().