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 |
| |
| arr_1d = np.array([1, 2, 3, 4, 5]) |
| print("1D Array:", arr_1d) |
| print("Type of the array:", type(arr_1d)) |
| |
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)) |
| print("Zeros Array:\n", zeros_arr) |
b) Creating an Array of Ones
| ones_arr = np.ones((2, 5)) |
| print("Ones Array:\n", ones_arr) |
c) Creating an Identity Matrix
| identity_matrix = np.eye(4) |
| 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) |
| print("Linspace Array:", linspace_arr) |
f) Creating a Random Array
| random_arr = np.random.rand(3, 3) |
| print("Random Array:\n", random_arr) |
Tip:
These functions are useful for machine learning, especially when initializing weights and datasets.