Basic Operations and Advanced Features of NumPy
NumPy goes beyond simple array operations to offer a variety of essential functions in data analysis and machine learning.
In this lesson, we'll delve into basic array operations, broadcasting, and random number generation.
Basic Array Operations
NumPy arrays support basic arithmetic operations, and these operations are carried out as follows:
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 automatically perform element-wise operations.
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 dynamically resize arrays aids significantly in data preprocessing.
3. Array Indexing and Slicing
In NumPy arrays, specific elements can be selected just like with 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.
Thus, even when array sizes don't match, broadcasting allows for efficient operations.
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 capabilities, useful for data 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.
You can swiftly create arrays, perform operations, and apply mathematical computations with ease.
References
NumPy's broadcasting feature allows operations between arrays of different sizes.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help