NumPy Advanced Indexing and Numerical Operations
NumPy Advanced Indexing and Numerical Operations
It provides a wide range of features for working with arrays, including advanced
indexing and numerical operations.
Fancy Indexing
Using Lists or Arrays of Indices Using Boolean Arrays Using Slicing with Fancy
Indexing
Selecting specific elements from an Indexing an array using a boolean array
array using lists or arrays of indices. with matching length. Combine fancy indexing with regular
slicing for more complex selections.
Using Lists or Arrays of Indices
import numpy as np
# Create a 1D array
arr = np.array([10, 20, 30, 40, 50])
print(result)
print(result)
Selecting a Range with Fancy Indices You can combine fancy indexing with
regular slicing.
You can use fancy indexing with slicing to select a range of
elements based on indices. This provides flexibility in arr = np.array([10, 20, 30, 40, 50])
selecting specific sub-arrays. indices = [1, 3] result = arr[indices[0]:indices[1]]
print(result)
output:[20 30]
Operations on NumPy Arrays
Basic Arithmetic Operations Scalar Operations Mathematical Functions
Perform element-wise arithmetic Perform arithmetic operations Use built-in mathematical functions for
operations on NumPy arrays. involving scalars, applied element- element-wise operations.
wise.
1. Addition
2. Subtraction
3. Multiplication
4. Division
Basic Arithmetic Operations
print(result_mul)
print(result_div)
Scalar Operations
# Adding a scalar
result_add_scalar = arr + 10
print(result_add_scalar) # Output: [11 12 13 14]
# Multiplying by a scalar
result_mul_scalar = arr * 2
print(result_mul_scalar) # Output: [2 4 6 8]
Mathematical Functions
Square Root Exponential Trigonometric Functions
The `np.sqrt()` function The `np.exp()` function calculates NumPy provides a collection of
calculates the square root of each the exponential of each element in trigonometric functions, including
element in a NumPy array. This is a NumPy array. This function is sine (`np.sin()`), cosine
useful for operations like useful for modeling exponential (`np.cos()`), and tangent
calculating the magnitude of growth, such as population (`np.tan()`). These functions are
vectors or transforming data for growth or compound interest. crucial for working with periodic
analysis. data, such as wave simulations,
signal processing, and analyzing
cyclical patterns.
result_sqrt = np.sqrt(arr)
result_exp = np.exp(arr)
mean_value = np.mean(arr)
Sum:
sum_value = np.sum(arr)
print(sum_value) Output: 15
Standard deviation
std_value = np.std(arr)