Basic Operations and Advanced Features of NumPy
NumPy goes beyond simple array operations, offering a variety of essential functions for data analysis and machine learning.
In this lesson, we’ll explore basic array operations, broadcasting, and random number generation.
Basic Array Operations
NumPy arrays support basic arithmetic operations, which are performed element-wise as shown below:
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) print(arr1 + arr2) # [5 7 9] print(arr1 * arr2) # [ 4 10 18] print(arr1 - arr2) # [-3 -3 -3] print(arr1 / arr2) # [0.25 0.4 0.5 ]
Unlike Python lists, NumPy arrays perform operations element-wise automatically.
2. Reshaping Arrays
NumPy makes it simple to change the shape of an array.
arr = np.array([1, 2, 3, 4, 5, 6]) # Convert to 2x3 matrix reshaped_arr = arr.reshape(2, 3) print(reshaped_arr)
The ability to reshape arrays dynamically is especially helpful in data preprocessing.
3. Array Indexing and Slicing
Specific elements in NumPy arrays can be selected similarly to Python lists.
arr = np.array([10, 20, 30, 40, 50]) print(arr[0]) # 10 print(arr[1:4]) # [20 30 40]
Elements in multi-dimensional arrays can also be specifically selected by row and column.
matrix = np.array([[1, 2, 3], [4, 5, 6]]) print(matrix[0, 1]) # 2 (second element in the first row) print(matrix[:, 1]) # [2 5] (second column of every row)
4. Broadcasting
Broadcasting
is a key NumPy feature that enables operations between arrays of different sizes.
arr1 = np.array([[1, 2, 3], [4, 5, 6]]) arr2 = np.array([10, 20, 30]) # `arr2` is automatically expanded across each row result = arr1 + arr2 print(result)
In the above example, although arr2
has a shape of (1,3)
, NumPy automatically expands it to (2,3)
for the operation.
This allows for efficient operations even when array shapes don't initially match.
5. Conditional Filtering
NumPy makes it easy to extract data using conditions.
arr = np.array([10, 20, 30, 40, 50]) # Select values greater than 30 filtered = arr[arr > 30] print(filtered)
6. Random Number Generation and Sampling
NumPy provides random number generation functions, which are useful for sampling and simulations.
# Generate 5 random numbers between 0 and 1 random_arr = np.random.rand(5) print(random_arr)
NumPy is a versatile library essential for AI and data science.
With NumPy, you can quickly create arrays, perform operations, and carry out mathematical computations with ease.
References
NumPy's broadcasting feature allows operations between arrays of different sizes.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help