Num Py
Num Py
Installing NumPy
Before diving into the code, you'll need to install NumPy. You can install it using pip:
import numpy as np
import numpy as np
Slicing Arrays
Slicing allows accessing a subset of the array. The syntax for slicing is start:stop:step.
Slicing 2D Arrays
python
Copy code
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr_2d[:2, 1:3]) # Output: [[2 3] [5 6]]
Broadcasting in Arrays
Broadcasting allows performing operations on arrays of different shapes. NumPy automatically
expands smaller arrays to match the shape of the larger ones.
Example: Broadcasting
python
Copy code
arr = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 2
result = arr + scalar
print(result)
# Output:
# [[3 4 5]
# [6 7 8]]
In finance, market cycles or interest rate seasonality can be cyclical. That means they follow a
pattern over time, like a wave—think about how the economy can rise and fall, just like a wave
goes up and down. This is where trigonometric functions like sin() (sine) come into play. The
sine function helps us model such wave-like patterns.
import numpy as np
cyclical_pattern = np.sin(time_period)
print(cyclical_pattern)
Real-World Interpretation
Imagine you're tracking interest rates over a year. Every quarter, the rate follows a wave-like
pattern:
• In quarter 1, it's neutral (interest rates are at the average level, represented by 0).
• In quarter 2, the rate peaks (interest rates go up, represented by 1).
• In quarter 3, the rate returns to the base level.
• (If we continued, quarter 4 might represent a dip or further cycle.)
This cyclical behavior can be used to predict market trends based on past performance, helping
financial analysts understand the highs and lows of interest rates or stock prices throughout the year.
The np.sin() function calculates the sine of an angle, which typically expects the angle to be
given in radians. However, the values you have provided (15, 21, 30, 45, 32) are not in
radians; they seem to be in degrees. If these values represent angles in degrees, you need to convert
them to radians first, because np.sin() works with radians.
time_period_radians = np.radians(time_period_degrees)
cyclical_pattern = np.sin(time_period_radians)
print(cyclical_pattern)
# Portfolio return
portfolio_return = np.dot(returns, weights)
print("Portfolio return:", portfolio_return)
Here, the 1D array of length 6 is reshaped into a 2D array with 2 rows and 3 columns.
Here, the 1D array is resized to a 2D array of shape (2, 3), and NumPy fills in the missing values by
repeating elements.
Flattening Arrays
Flattening converts a multi-dimensional array into a one-dimensional array. NumPy provides two
functions for this: ravel() and flatten().
Transposing Arrays
Transposing is a common operation for swapping the axes of an array. You can transpose arrays
using transpose() or by simply using .T.
Splitting Arrays
Arrays can also be split into multiple smaller arrays using hsplit() for horizontal splitting and
vsplit() for vertical splitting.
Example: Vertical Splitting
python
Copy code
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
split_arr = np.vsplit(arr, 2)
print(split_arr)
# Output:
# [array([[1, 2],
# [3, 4]]),
# array([[5, 6],
# [7, 8]])]
Aggregation Functions
Aggregation functions perform calculations such as sum, product, mean, minimum, and maximum
on the elements of arrays.
Matrix Operations
NumPy supports matrix operations such as dot product and cross product.
Random Distributions
NumPy also allows generating numbers based on statistical distributions.
In supply chain management, forecasting product demand is crucial. Random number generation
can simulate varying demand scenarios.
Example: Generating Random Numbers
python
Copy code
import numpy as np
# Simulating product demand forecast for 3 products over 2 weeks
random_demand = np.random.random((2, 3)) * 100
print(random_demand)
# Output:
# [[12.34 56.78 91.01]
# [34.56 78.90 11.21]]
Here, each random number represents the forecasted demand (scaled up to 100 units) for different
products across two weeks.
Chapter 9: Linear Algebra with NumPy
Linear algebra is a key part of scientific computation. NumPy provides efficient ways to perform
matrix operations, solve systems of equations, and compute matrix properties.
Matrix Multiplication
You can perform matrix multiplication using the dot() or matmul() function.
Determinant of a Matrix
The determinant of a matrix can be computed using np.linalg.det().
In robotics, matrix multiplication can be used to compute transformations for moving a robotic arm.
Example: Matrix Multiplication
Fancy Indexing
Fancy indexing refers to indexing using arrays of indices, allowing for complex selections.
arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
indices = np.array([[0, 1], [1, 2]]) # Selecting specific indices
selected_elements = arr[indices]
print(selected_elements)
# Output:
# [[10 20]
# [50 60]]
This approach allows for selective access to array elements based on the provided indices.
Boolean Indexing
Boolean indexing enables array selection based on conditions.
Here, we filter an array to include only those elements that meet a specific condition.
Use Case: Image Processing - Selecting Pixel Regions
Fancy indexing can help isolate regions of interest in an image, like selecting specific pixels from
an image matrix.
Example: Fancy Indexing for Image Pixel Selection
This selects specific regions from the image for further processing.
Use Case: Customer Data Analysis - Filtering VIP Customers
Boolean indexing can be used to filter customers who meet certain criteria, like selecting customers
with purchases over a certain threshold.
Example: Boolean Indexing for Filtering Customer Data
This selects only the customers with purchases greater than $2,000.
Chapter: Case Studies & Real-World Examples
Introduction
In this chapter, we explore real-world applications of NumPy in various domains
Scenario
Analyzing patient health metrics to assess treatment effectiveness.
Example
Using NumPy to evaluate changes in blood pressure readings.
python
Copy code
import numpy as np
Insights
By evaluating patient metrics, healthcare providers can assess treatment effectiveness and make
data-driven decisions for improving patient care.