Introduction
NumPy arrays are the **core data structure** of NumPy. They are **faster and more memory-efficient** than Python lists, and support **vectorized operations**. In this blog, we explore arrays with practical examples and assignments.
1. Creating NumPy Arrays
import numpy as np # From list arr1 = np.array([1,2,3,4,5]) # 2D Array arr2 = np.array([[1,2,3],[4,5,6]]) # Using arange arr3 = np.arange(0,10,2) # Using linspace arr4 = np.linspace(0,1,5) # Zeros and Ones zeros = np.zeros((2,3)) ones = np.ones((3,2))
2. Array Attributes
arr = np.array([[1,2,3],[4,5,6]]) print(arr.shape) # (2,3) print(arr.size) # 6 print(arr.ndim) # 2 print(arr.dtype) # int64
3. Indexing and Slicing
arr = np.array([10,20,30,40,50]) print(arr[0]) # 10 print(arr[-1]) # 50 print(arr[1:4]) # [20 30 40] # 2D slicing arr2d = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(arr2d[:,2]) # [3 6 9] -> last column print(arr2d[1,:]) # [4 5 6] -> second row
4. Array Operations
a = np.array([1,2,3]) b = np.array([4,5,6]) # Arithmetic print(a + b) # [5 7 9] print(a * b) # [4 10 18] print(a - b) # [-3 -3 -3] print(a / b) # [0.25 0.4 0.5] # Functions print(np.sqrt(a)) # [1.0 1.414 1.732] print(np.sum(a)) # 6 print(np.mean(b)) # 5.0
5. Reshaping, Flattening, Transpose
arr = np.arange(1,10) reshaped = arr.reshape(3,3) print(reshaped) flat = reshaped.flatten() print(flat) # [1 2 3 4 5 6 7 8 9] # Transpose print(reshaped.T)
6. Boolean Indexing & Filtering
arr = np.array([10,20,30,40,50]) filtered = arr[arr > 25] print(filtered) # [30 40 50] # Multiple conditions filtered2 = arr[(arr>15) & (arr<45)] print(filtered2) # [20 30 40]
7. Random Arrays
rand_arr = np.random.randint(1,100, size=(3,3)) print(rand_arr) rand_float = np.random.rand(2,4) # 2x4 random floats [0,1) print(rand_float)
8. Assignments with Show Answer Buttons
Assignment 1: Create a 1D array from 1 to 20 and print only even numbers.
import numpy as np arr = np.arange(1,21) even_numbers = arr[arr % 2 == 0] print(even_numbers)
Assignment 2: Create a 3x3 random integer array and print the sum of each column.
import numpy as np arr = np.random.randint(1,10,(3,3)) print(arr) col_sum = np.sum(arr, axis=0) print(col_sum)
Assignment 3: Create a 4x4 array of ones and replace the diagonal with 5.
import numpy as np arr = np.ones((4,4)) np.fill_diagonal(arr, 5) print(arr)
Assignment 4: Create an array [1,2,3,4,5] and compute sqrt, square, and cube of each element.
import numpy as np arr = np.array([1,2,3,4,5]) print("Sqrt:", np.sqrt(arr)) print("Square:", arr**2) print("Cube:", arr**3)
9. Summary
NumPy arrays are powerful for numerical computing. With array creation, indexing, slicing, reshaping, operations, and filtering, you can handle data efficiently. Assignments help you practice the concepts.
Learn More on NumPy Docs
0 Comments