## Saturday 13 April 2024

### Operations on Numpy Arrays

the various transformations and computations you can perform:

1. Element-wise Arithmetic

• Basic Operations: NumPy supports addition (+), subtraction (-), multiplication (*), division (/), and more, directly on arrays.
Python
import numpy as np

arr1 = np.array([2, 5, -1, 4])
arr2 = np.array([1, 2, 5, -2])

result_sub = arr1 - arr2
result_mul = arr1 * arr2
result_div = arr1 / arr2

• Universal Functions: NumPy provides mathematical functions that operate on each element of an array.
Python
# Square root, exponent, trigonometric functions
sqrt_array = np.sqrt(arr1)
exp_array = np.exp(arr1)
sin_array = np.sin(arr1)

2. Statistical Calculations

• Measures of Central Tendency:

• np.mean(): Mean (average)

• np.median(): Median

• np.std(): Standard deviation

• np.var(): Variance

• Other Statistics:

• np.min(), np.max(): Minimum and maximum values

• np.sum(): Sum of array elements

• np.correlate(): Correlation between arrays

3. Matrix Operations (Linear Algebra)

• Matrix Multiplication: Use np.dot() for the dot product of matrices.
Python
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result_matrix = np.dot(matrix1, matrix2)

• Other Linear Algebra Functions:

• np.linalg.inv(): Matrix inverse

• np.linalg.eig(): Eigenvalues and eigenvectors

• np.linalg.det(): Determinant

• Operations on Compatible Arrays: NumPy can perform operations between arrays with different but compatible shapes. It follows specific broadcasting rules.
Python
arr = np.array([1, 2, 3])
result = arr + 5

5. Array Manipulation

• Reshaping: Change the arrangement of elements using reshape().
Python
new_shape_array = arr.reshape(2, 6)

• Transposing: Swap rows and columns with transpose() or .T.
Python
transposed_array = matrix1.T

• Concatenation: Combine arrays with np.concatenate , np.vstack, np.hstack.

6. Comparison and Boolean Operations

• Element-wise Comparisons: NumPy supports >, <, >=, <=, == (equality), and != (not equal), resulting in boolean arrays.

• Logical Operators:

• np.all(): Check if all elements are True.

• np.any(): Check if at least one element is True.

comparison and boolean operations within the world of NumPy arrays.

1. Element-wise Comparisons

NumPy allows you to compare arrays element by element using familiar comparison operators:

• > (greater than)

• < (less than)

• >= (greater than or equal to)

• <= (less than or equal to)

• == (element-wise equality)

• != (element-wise inequality)

Result: Boolean Arrays: The outcome of these comparisons is a boolean NumPy array with the same shape as the original, containing True where the condition holds and False otherwise.

Example:

Python

import numpy as np

arr = np.array([5, 1, -2, 10, 5])

boolean_mask = arr > 3   # Find elements greater than 3
print(boolean_mask)       # Output: [ True False False  True  True]

values_less_than_5 = arr[arr < 5# Select elements less than 5
print(values_less_than_5)  # Output: [ 1 -2]

2. Logical Operators

• np.logical_and(arr1, arr2): Element-wise 'and' operation between two boolean arrays.

• np.logical_or(arr1, arr2): Element-wise 'or' operation.

• np.logical_not(arr): Element-wise negation ('not' operation).

Example: Combining Conditions

Python

condition1 = arr > 3
condition2 = arr < 8

Applications of Boolean Arrays

1. Filtering/Indexing: Use boolean arrays to select elements meeting specific criteria (as shown in the examples).

2. Conditional Modification: Update array elements based on conditions.
Python
arr[arr < 0] = 0  # Replace negative values with 0

3. Counting: Count occurrences satisfying a condition.
Python
count_positive = np.count_nonzero(arr > 0)

Key Points

• Shape Matters: For comparisons or logical operations between arrays, they typically need to have the same shape or be broadcastable.

• Boolean Indexing: Is a powerful way to manipulate arrays based on conditions.

Practice Exercises

1. In an array representing student grades, find the indices of the students who passed (grade >= 60).

2. Given two arrays representing temperature measurements, create a boolean mask indicating where the measurements from the first array exceed those of the second array.

## In an array representing student grades, find the indices of the students who passed (grade >= 60).

Steps

1. Create an Array of Student Grades:
Python
import numpy as np

grades = np.array([75, 52, 86, 65, 93, 48])

Python

3. Find Indices Using np.where():
Python
print(passing_indices)  # Output: (array([0, 2, 3, 4]),)

Explanation

• np.where(passing_mask): The np.where() function returns the indices of elements where the condition (in this case, passing_mask) is True.

Directly Accessing Passing Students

You can use the indices to directly access the passing grades:

Python

print(passing_grades)  # Output: [75 86 65 93]

Given two arrays representing temperature measurements, create a boolean mask indicating where the measurements from the first array exceed those of the second array.

Steps

1. Sample Temperature Arrays:
Python
import numpy as np

temp_array1 = np.array([25, 18, 32, 21])
temp_array2 = np.array([22, 19, 28, 20])

2. Comparison:
Python
print(comparison_mask)  # Output: [ True False  True  True]

Python
print(higher_temps)   # Output:  [25 32 21]

Explanation

1. temp_array1 > temp_array2: NumPy performs this comparison element-wise, generating a boolean array where each element is True if the corresponding temperature in temp_array1 is greater than that in temp_array2.

2. Indexing with the Mask: We use this comparison_mask to select only the elements from temp_array1 where the condition held, giving us the higher temperatures.

Key Points

• Arrays of Equal Shape: For this direct comparison, the temperature arrays need to have the same shape.

• Boolean Masking: The boolean mask acts as a filter, allowing you to precisely extract the elements of interest.