NumPy: Advanced Indexing
and Numerical Operations
NumPy is a powerful Python library for numerical computing.
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
Selecting by Index Multiple Indices Array of Indices
Use a list of indices to select specific Select multiple elements by providing a Use an array of indices to select
elements from an array. list of corresponding indices. elements in a more structured manner.
import numpy as np
# Create a 1D array
arr = np.array([10, 20, 30, 40, 50])
# Fancy indexing: selecting elements by indices
indices = [0, 2, 4]
result = arr[indices]
print(result)
# Output: [10 30 50]
Using Boolean Arrays
Boolean Array for Filtering Applying the Mask Code Example
A boolean array, also known as a mask, When you index an array with a boolean Here's a code example demonstrating
can be used to filter an array, selecting array, the resulting array will only how to use a boolean array to filter an
only elements where the corresponding contain the elements where the array:
value in the mask is True. corresponding value in the mask is True.
arr = np.array([10, 20, 30, 40, 50])
# Create a boolean array
mask = arr > 25
result = arr[mask]
print(result)
# Output: [30 40 50]
Using Slicing with Fancy Indexing
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
Addition Subtraction Multiplication Division
In NumPy, addition is Similar to addition, Element-wise Division in NumPy is also
performed element-wise subtraction in NumPy is multiplication is another element-wise, using the
on arrays. You can add also performed element- fundamental arithmetic `/` operator. When
two arrays of the same wise. The `-` operator is operation in NumPy. You dividing two arrays, the
shape using the `+` used to subtract two can multiply two arrays operation is performed
operator. arrays with matching of the same shape using on corresponding
shapes. the `*` operator. elements.
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([5, 6, 7, 8])
Output:
[ 6 8 10 12]
result_add = arr1 + arr2
[-4 -4 -4 -4]
print(result_add)
[ 5 12 21 32]
result_sub = arr1 - arr2
[0.2 0.33333333 0.42857143 0.5]
print(result_sub)
result_mul = arr1 * arr2
print(result_mul)
result_div = arr1 / arr2
print(result_div)
Scalar Operations
Adding a scalar Multiplying by a scalar
In NumPy, scalar addition involves adding a single value (the Scalar multiplication, on the other hand, multiplies each
scalar) to each element of the array. element of the array by the scalar.
arr = np.array([1, 2, 3, 4])
# 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.
arr = np.array([1, 4, 9, 16])
#Square root of each element
result_sqrt = np.sqrt(arr)
print(result_sqrt) Output: [1. 2. 3. 4.]
#Exponential of each element
result_exp = np.exp(arr)
print(result_exp) Output: [2.71828183e+00 5.45981500e+01 8.10308393e+03 8.88611052e+06]
Statistical Operations
Mean Sum Standard Deviation Minimum and
Maximum
The mean calculates the The sum calculates the The standard deviation
average value of all total of all elements in an measures the spread or The minimum and
elements in an array. array. variability of data points maximum functions find
around the mean. the smallest and largest
values within an array.
arr = np.array([1, 2, 3, 4, 5])
MEAN :
mean_value = np.mean(arr)
print(mean_value) Output: 3.0
Sum:
sum_value = np.sum(arr)
print(sum_value) Output: 15
Standard deviation
std_value = np.std(arr)
print(std_value) Output: 1.4142135623730951