NumPy: Data Generation
✕Generating Different Matrix types
Matrix Generation Functions in NumPy:
| Function | Description | Example |
|---|---|---|
np.zeros | Generates an array filled with zeros. | np.zeros((2, 3)) => [[0., 0., 0.], [0., 0., 0.]] |
np.ones | Generates an array filled with ones. | np.ones((3, 2), dtype=int) => [[1, 1], [1, 1], [1, 1]] |
np.full | Generates an array filled with given value. | np.full((2, 2), 7) => [[7, 7], [7, 7]] |
np.identity | Generates an identity matrix. | np.identity(3) => [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]] |
Examples for generating different types of matrices in NumPy
Generating Random Data
Random Data Generation Functions in NumPy:
| Function | Description | Example |
|---|---|---|
np.random.rand | Generates an array of given shape with random values between 0 and 1. | np.random.rand(2, 3) => [[0.5488135, 0.71518937, 0.60276338], [0.54488318, 0.4236548, 0.64589411]] |
np.random.seed | Sets the seed for random number generation to ensure reproducibility. | np.random.seed(42) |
np.random.randint | Generates an array of given shape with random integers from a specified range. | np.random.randint(1, 10, size=(2, 2)) => [[5, 8], [9, 5]] |
np.random.normal | Generates an array of given shape with random samples from a normal distribution. | np.random.normal(20, 5, size=(2, 3)) => [[18.23, 22.45, 19.87], [21.34, 17.56, 24.78]] |
np.random.choice | Generates an array of given shape by randomly sampling from a given 1-D array. | np.random.choice([10, 20, 30], size=(2, 3)) => [[20, 10, 30], [10, 20, 20]] |
Examples for generating random data in NumPy
Generating Sequences
Sequence Generation Functions in NumPy:
| Function | Description | Example |
|---|---|---|
np.arange | Evenly spaced values within a given interval. (like range) | np.arange(0, 10, 2) => [0, 2, 4, 6, 8] |
np.linspace | Evenly spaced values between a specified start and end. | np.linspace(0, 1, 5) => [0., 0.25, 0.5, 0.75, 1.] |
np.geomspace | Numbers spaced evenly on a geometric progression. | np.geomspace(2, 32, 5) => [2., 4., 8., 16., 32.] |
Examples for generating sequences and grids in NumPy
