Here’s an example of how to create a random 2D array using NumPy in Python:
import numpy as np
array = np.random.rand(5, 3) # creates a 5x3 array with random values between 0 and 1
print(array)
You can also create an array of zeros or ones using the np.zeros()
or np.ones()
functions:
array_zeros = np.zeros((2,3) # creates a 2x3 array with all zeros
array_ones = np.ones((5,4) # creates a 5x4 array with all ones
You can also create an array of specific values using the np.array()
function:
my_array = np.array([[1,2,3],[4,5,6]]) # creates a 2x3 array with specific values
print(my_array)
You can also create an identity matrix (a square matrix with diagonal elements of 1 and other elements as 0) using the np.eye()
function:
identity = np.eye(3) # creates a 3x3 identity matrix
print(identity)
You can also create an array with specific values along one or more dimensions using the np.full()
function:
zeros_1d = np.full((5,), 0) # creates a 1D array of zeros with length 5
ones_2d = np.full((2,3), 1) # creates a 2D array of ones with dimensions 2x3
You can also create an array using specific values and reshape it to a different shape using the np.reshape()
function:
my_array = np.arange(1,7) # creates a 1D array with values [1,2,3,4,5,6]
reshaped_array = my_array.reshape((2,3)
print(reshaped_array) # reshapes the array to 2x3 matrix [[1,2,3],[4,5,6]]
These are just some examples of how you can create numpy arrays in Python using NumPy. The library has many more functions for creating and manipulating arrays that can help you do all sorts of mathematical operations on your data.