1. Creating Arrays with np.array()
The np.array()
function is the most basic way to create an array from a list or a list of lists.
import numpy as np
# Creating a 1D array
arr_1d = np.array([1, 2, 3, 4])
print("1D array:\n", arr_1d)
# Creating a 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D array:\n", arr_2d)
Python2. Creating Arrays with np.zeros()
To create an array filled with zeros, you can use np.zeros()
. It’s useful for initializing arrays.
# Creating a 2D array of zeros
zeros_array = np.zeros((2, 3)) # Shape as (rows, columns)
print("2D zeros array:\n", zeros_array)
Python3. Creating Arrays with np.ones()
Similarly, np.ones()
creates an array filled with ones.
# Creating a 3D array of ones
ones_array = np.ones((2, 2, 3)) # Shape as (depth, rows, columns)
print("3D ones array:\n", ones_array)
Python4. Creating Arrays with np.arange()
np.arange()
creates an array with a range of numbers. It’s similar to Python’s range()
but returns an array.
# Creating an array with a range from 0 to 9
range_array = np.arange(10)
print("Range array:\n", range_array)
Python5. Creating Arrays with np.linspace()
np.linspace()
creates an array with evenly spaced numbers over a specified interval.
# Creating an array with 5 values, evenly spaced between 0 and 1
linspace_array = np.linspace(0, 1, 5)
print("Linspace array:\n", linspace_array)
Python6. Creating Arrays with np.eye()
np.eye()
creates an identity matrix, useful for linear algebra.
# Creating a 3x3 identity matrix
identity_matrix = np.eye(3)
print("Identity matrix:\n", identity_matrix)
Python7. Creating Arrays with np.random.rand()
To create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1)
.
# Creating a 2x2 array with random numbers
random_array = np.random.rand(2, 2)
print("Random array:\n", random_array)
PythonPractical Example
Let’s combine some of these methods in a practical example:
import numpy as np
# Create a 4x4 array of zeros
base_array = np.zeros((4, 4))
# Fill the first row with ones
base_array[0] = np.ones(4)
# Create a 2x2 identity matrix and place it in the bottom right corner
base_array[2:, 2:] = np.eye(2)
print("Custom array:\n", base_array)
Python