Creating NumPy Arrays
A NumPy array is the fundamental building block of the NumPy library. Unlike Python lists, NumPy arrays provide a more efficient, faster, and memory-optimized way to store and manipulate numerical data.
1. Creating a NumPy Array from a List
import numpy as np
# Creating a 1D array from a list
arr_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:", arr_1d)
print("Type of the array:", type(arr_1d))
# Verify it's a NumPy array
Note: Unlike Python lists, NumPy arrays provide faster numerical operations and take up less memory.
2. Creating Multi-Dimensional Arrays
You can also create 2D and 3D arrays in NumPy:
# Creating a 2D NumPy array (Matrix)
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D Array:\n", arr_2d)
# Creating a 3D NumPy array (Tensor)
arr_3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print("3D Array:\n", arr_3d)
Key Differences:
- 1D Array: A simple list of numbers
- 2D Array: A matrix (rows & columns)
- 3D Array: A collection of 2D arrays
3. Creating Special NumPy Arrays
NumPy provides several built-in functions to create arrays quickly:
a) Creating an Array of Zeros
zeros_arr = np.zeros((3, 3)) # Creates a 3x3 matrix filled with zeros
print("Zeros Array:\n", zeros_arr)
b) Creating an Array of Ones
ones_arr = np.ones((2, 5)) # Creates a 2x5 matrix filled with ones
print("Ones Array:\n", ones_arr)
c) Creating an Identity Matrix
identity_matrix = np.eye(4) # Creates a 4x4 identity matrix
print("Identity Matrix:\n", identity_matrix)
d) Creating an Array with a Range of Values
range_arr = np.arange(1, 11, 2) # Creates an array with values from 1 to 10 with a step of 2
print("Range Array:", range_arr)
e) Creating an Array with Evenly Spaced Values
linspace_arr = np.linspace(0, 1, 5) # Creates 5 evenly spaced values between 0 and 1
print("Linspace Array:", linspace_arr)
f) Creating a Random Array
random_arr = np.random.rand(3, 3) # Generates a 3x3 array of random values between 0 and 1
print("Random Array:\n", random_arr)
Tip:
These functions are useful for machine learning, especially when initializing weights and datasets.