[go: up one dir, main page]

0% found this document useful (0 votes)
18 views25 pages

Num Py

py

Uploaded by

jaindrew1999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views25 pages

Num Py

py

Uploaded by

jaindrew1999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

NumPy Essentials: A Complete Guide

Chapter 1: Introduction to NumPy


What is NumPy?
NumPy (Numerical Python) is the core library for scientific computing in Python. It provides a
high-performance multidimensional array object, and tools for working with these arrays. NumPy is
incredibly fast, making it suitable for tasks such as linear algebra, statistical analysis, and even
machine learning. It's often used in combination with other libraries like Pandas and Matplotlib.

Installing NumPy
Before diving into the code, you'll need to install NumPy. You can install it using pip:

pip install numpy

After installation, import it in your code:

import numpy as np

The alias np is commonly used for convenience.

Why Use NumPy?


NumPy offers the following advantages:
• Efficiency: NumPy arrays are more compact and faster than Python lists.
• Mathematical operations: Operations on arrays are performed element-wise, allowing for
efficient computation.
• Array Manipulation: NumPy provides easy-to-use functions for reshaping, slicing,
stacking, and broadcasting arrays.
• Integration: It integrates seamlessly with other libraries like Pandas, Matplotlib, and Scikit-
learn.
Real-Time Use Case:
In financial analysis, managing large datasets of stock prices or currency rates is crucial. NumPy’s
arrays help store and manipulate this data efficiently. For example, an analyst can use NumPy to
calculate daily stock returns or analyze the volatility of different assets over time.
Practical Example:
import numpy as np

# Simulating daily stock price data for 5 days


stock_prices = np.array([100, 102, 101, 104, 105])

# Calculating daily returns


returns = np.diff(stock_prices) / stock_prices[:-1]
print("Daily returns:", returns)
Chapter 2: NumPy Arrays
Creating Arrays
A NumPy array is a grid of values, all of the same type, indexed by a tuple of non-negative integers.
Arrays are created using the array() function.

Example: Creating a 1D Array

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


print(arr)

Example: Creating a 2D Array

arr_2d = np.array([[1, 2, 3], [4, 5, 6]])


print(arr_2d)

Array Creation Functions


NumPy provides several array creation functions that help initialize arrays of specific shapes and
values. Here are a few:

1. Creating an Array of Zeros

zeros_arr = np.zeros((3, 4))


print(zeros_arr)

This creates a 3x4 array filled with zeros.

2. Creating an Array of Ones

ones_arr = np.ones((2, 3))


print(ones_arr)

This creates a 2x3 array filled with ones.

3. Creating an Array with a Range of Numbers

range_arr = np.arange(0, 10, 2)


print(range_arr)

This creates an array starting from 0, going up to 10, with a step of 2.

4. Creating an Array with Linearly Spaced Numbers


python
Copy code
linspace_arr = np.linspace(0, 1, 5)
print(linspace_arr)
This creates an array of 5 numbers evenly spaced between 0 and 1.
Real-Time Use Case:
In machine learning, you often represent features of data samples as arrays. For instance, each row
in a NumPy array can represent a sample, and each column can represent a feature like the age,
income, or spending score of customers.
Practical Example:
import numpy as np

# Creating an array for customer features (age, income, spending score)


customer_data = np.array([[25, 50000, 60], [30, 60000, 70], [45, 80000, 50]])

# Access the data of the first customer


first_customer = customer_data[0]
print("First customer data:", first_customer)
Chapter 3: Indexing, Slicing, and Iterating
Indexing One-Dimensional Arrays
Indexing in NumPy is similar to lists in Python. The index starts from 0, and negative indices can be
used to access elements from the end.

Example: Indexing a 1D Array


python
Copy code
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # Output: 10
print(arr[-1]) # Output: 50

Indexing Multi-Dimensional Arrays


For multi-dimensional arrays, a tuple of indices is used to access elements.

Example: Indexing a 2D Array


python
Copy code
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d[1, 2]) # Output: 6

Slicing Arrays
Slicing allows accessing a subset of the array. The syntax for slicing is start:stop:step.

Example: Slicing a 1D Array


python
Copy code
arr = np.array([0, 1, 2, 3, 4, 5, 6])
print(arr[1:5]) # Output: [1 2 3 4]
print(arr[::2]) # Output: [0 2 4 6]

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]]

Modifying Array Elements


You can easily modify array elements by assigning new values to specific indices or slices.

Example: Modifying Elements


python
Copy code
arr = np.array([10, 20, 30, 40])
arr[0] = 100
print(arr) # Output: [100 20 30 40]
Iterating through Arrays
You can iterate over arrays using loops.

Example: Iterating a 1D Array


python
Copy code
for x in np.array([1, 2, 3]):
print(x)

Example: Iterating a 2D Array


python
Copy code
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
for row in arr_2d:
print(row)

Real-Time Use Case:


A data scientist may want to analyze a subset of financial data for a specific period. For example,
extracting stock prices for the last quarter from a year’s data array.
Practical Example:
import numpy as np

# Simulating stock prices for a year (365 days)


stock_prices = np.random.normal(100, 10, 365)

# Extracting prices from the last quarter (last 90 days)


last_quarter_prices = stock_prices[-90:]
print("Last quarter stock prices:", last_quarter_prices)
Chapter 4: Array Operations
Arithmetic Operations on Arrays
You can perform element-wise arithmetic operations on NumPy arrays. These operations are
applied to each element of the array individually.

Example: Array Addition


python
Copy code
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = arr1 + arr2
print(result) # Output: [5 7 9]

Example: Array Multiplication


python
Copy code
arr = np.array([1, 2, 3])
result = arr * 2
print(result) # Output: [2 4 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]]

Universal Functions (ufuncs)


NumPy has a range of built-in universal functions (ufuncs) that perform element-wise operations.

Example: Applying sin() Function


python
Copy code
arr = np.array([0, np.pi/2, np.pi])
result = np.sin(arr)
print(result) # Output: [0. 1. 0.]
Explanation:
Trigonometric Functions and Cycles

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.

Understanding Sine Function


The sin() function takes an angle (in radians) as input and returns a value between -1 and 1.
This value describes the height of the wave at different points in time:
• sin(0) = 0 (the wave starts at 0)
• sin(π/2) = 1 (the wave peaks at 1)
• sin(π) = 0 (the wave comes back to 0)
• sin(3π/2) = -1 (the wave dips down to -1)
• sin(2π) = 0 (the wave returns to 0)

How This Relates to Finance


Now, let's assume you're trying to model how interest rates or market conditions follow a seasonal
or cyclical trend every quarter (3 months).
• Time period in quarters: This means we are looking at how the market behaves every
quarter.
• Angles (in radians): We use angles in radians to represent these time periods. The sine
function will output values that we can interpret as how "high" or "low" the market or
interest rate is at each quarter.
Example:

import numpy as np

# Time period in quarters (expressed as angles in radians)

time_period = np.array([0, np.pi/2, np.pi])

# Calculate the cyclical pattern

cyclical_pattern = np.sin(time_period)

print(cyclical_pattern)

time_period: This array represents different points in time


(quarters) converted to angles.

• 0 radians represents the start of the cycle (quarter 1).


• π/2 radians (around 1.57) represents the peak of the cycle (quarter 2).
• π radians (around 3.14) represents the mid-point of the cycle, where the value returns
to 0 (quarter 3).
• cyclical_pattern: This is the sine value for each point in the cycle, giving the following
output:
• sin(0) = 0: The market is at the base level at quarter 1.
• sin(π/2) = 1: The market is at its peak at quarter 2.
• sin(π) = 0: The market returns to the base level at quarter 3.

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.

Visualization of the Sine Wave:


• Think of a wave that starts at 0, rises to a peak (like a hill), and falls back to 0.
• This wave pattern can describe how something fluctuates over time, whether it's stock
prices, interest rates, or even economic growth.

Understanding the np.sin() Function

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.

Radians vs. Degrees


• Degrees: This is a common way to measure angles (e.g., 90°, 180°, etc.).
• Radians: Another way to measure angles, where:
• 180° = π radians
• 90° = π/2 radians
• 360° = 2π radians
If you input degrees directly without conversion, np.sin() will interpret them as radians, leading
to unexpected results.

Correct Process with Degree Conversion:


You need to first convert degrees to radians using np.radians(). Then, apply the np.sin()
function to get the correct results.

Example with Conversion:


Here’s how to properly calculate the sine of the angles in degrees:
import numpy as np

# Time period in quarters (expressed as angles in degrees)

time_period_degrees = np.array([15, 21, 30, 45, 32])

# Convert degrees to radians

time_period_radians = np.radians(time_period_degrees)

# Calculate the cyclical pattern

cyclical_pattern = np.sin(time_period_radians)

print(cyclical_pattern)

Convert degrees to radians:

• The values [15, 21, 30, 45, 32] are in degrees.


• To convert degrees to radians:

Real-Time Use Case:


In financial modeling, calculating portfolio performance involves multiplying each stock's returns
by its weight in the portfolio and summing the results.
Practical Example:
import numpy as np

# Stock returns of 3 assets in a portfolio


returns = np.array([0.05, 0.02, -0.01])

# Weights of each asset in the portfolio


weights = np.array([0.4, 0.4, 0.2])

# Portfolio return
portfolio_return = np.dot(returns, weights)
print("Portfolio return:", portfolio_return)

Your Code Breakdown


In your code:
• returns = np.array([0.05, 0.02, -0.01]): This is the array of returns for 3
assets. For example:
• Asset 1 has a return of 5% (0.05).
• Asset 2 has a return of 2% (0.02).
• Asset 3 has a return of -1% (-0.01).
• weights = np.array([0.4, 0.4, 0.2]): These are the weights of each asset in
the portfolio. For example:
• 40% of the portfolio is invested in Asset 1.
• 40% of the portfolio is invested in Asset 2.
• 20% of the portfolio is invested in Asset 3.
To calculate the portfolio return, the dot product multiplies each return by its respective weight
and sums them up:
portfolio_return=(0.05×0.4)+(0.02×0.4)+(−0.01×0.2)
Breaking it down step-by-step:
1. Asset 1: 0.05×0.4=0.02
2. Asset 2: 0.02×0.4=0.008
3. Asset 3: −0.01×0.2=−0.002
Now, sum these up:
portfolio_return=0.02+0.008−0.002=0.026
Thus, the portfolio return is 0.026, or 2.6%.
Chapter 5: Reshaping and Resizing Arrays
Reshaping Arrays with reshape()
Reshaping means changing the shape of an array without changing its data. You can convert a 1D
array into a 2D array, or even higher dimensions, using the reshape() function.

Example: Reshaping a 1D Array to 2D


python
Copy code
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape((2, 3))
print(reshaped_arr)
# Output:
# [[1 2 3]
# [4 5 6]]

Here, the 1D array of length 6 is reshaped into a 2D array with 2 rows and 3 columns.

Resizing Arrays with resize()


Unlike reshape(), which returns a new reshaped array, resize() changes the shape of the
array in place. If you resize to a shape that requires more elements than are in the original array,
NumPy will fill the array with repeated copies of the data.

Example: Resizing an Array


python
Copy code
arr = np.array([1, 2, 3, 4])
arr.resize((2, 3))
print(arr)
# Output:
# [[1 2 3]
# [4 1 2]]

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().

Example: Flattening a 2D Array


python
Copy code
arr = np.array([[1, 2, 3], [4, 5, 6]])
flat_arr = arr.flatten()
print(flat_arr) # Output: [1 2 3 4 5 6]

Difference Between ravel() and flatten()


• flatten() always returns a copy of the array.
• ravel() returns a flattened array but tries to avoid copying data if possible (returns a
reference).

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.

Example: Transposing a 2D Array


python
Copy code
arr = np.array([[1, 2], [3, 4], [5, 6]])
transposed_arr = arr.T
print(transposed_arr)
# Output:
# [[1 3 5]
# [2 4 6]]

Stacking and Splitting Arrays


NumPy allows stacking and splitting arrays, which helps in efficiently combining and breaking
apart arrays.

Horizontal and Vertical Stacking


• hstack() stacks arrays horizontally (column-wise).
• vstack() stacks arrays vertically (row-wise).

Example: Horizontal Stacking


python
Copy code
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
stacked_arr = np.hstack((arr1, arr2))
print(stacked_arr) # Output: [1 2 3 4 5 6]

Example: Vertical Stacking


python
Copy code
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
stacked_arr = np.vstack((arr1, arr2))
print(stacked_arr)
# Output:
# [[1 2]
# [3 4]
# [5 6]
# [7 8]]

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]])]

Real-Time Use Case:


When training machine learning models, image data (originally a flat array of pixel values) needs to
be reshaped into a 3D array format (height, width, color channels) for model input.
Practical Example:
import numpy as np

# Simulating pixel values of a 6x6 grayscale image


image_data = np.array([i for i in range(36)])

# Reshaping the flat array into a 2D array (6x6 image)


reshaped_image = image_data.reshape((6, 6))
print("Reshaped image data:\n", reshaped_image)
Chapter 6: Array Manipulation
Joining Arrays
You can combine arrays using the concatenate() function. It can combine arrays along any
specified axis.

Example: Concatenating Arrays


python
Copy code
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6]])
concat_arr = np.concatenate((arr1, arr2), axis=0)
print(concat_arr)
# Output:
# [[1 2]
# [3 4]
# [5 6]]

Adding/Removing Elements from Arrays


NumPy provides functions like append(), insert(), and delete() for manipulating the
content of arrays.

Example: Appending an Element


python
Copy code
arr = np.array([1, 2, 3])
new_arr = np.append(arr, 4)
print(new_arr) # Output: [1 2 3 4]

Example: Deleting an Element


python
Copy code
arr = np.array([1, 2, 3, 4])
new_arr = np.delete(arr, 1)
print(new_arr) # Output: [1 3 4]

Real-Time Use Case:


In financial modelling, broadcasting can apply changes across entire datasets, such as adjusting
stock prices for inflation or currency exchange rates.
Practical Example:
import numpy as np

# Stock prices of two assets over three days


prices = np.array([[100, 200], [102, 205], [105, 210]])

# Inflation factor to adjust prices


inflation = 1.02

# Adjusting for inflation


adjusted_prices = prices * inflation
print("Adjusted prices:\n", adjusted_prices)

1. Inflation-Adjusted Investment Returns


• Scenario: Suppose you're analyzing the historical performance of a portfolio of stocks.
Nominal stock prices do not reflect the impact of inflation, so you need to adjust prices to
calculate the real rate of return.
• Real-Time Use Case: Financial analysts adjust stock prices using inflation data to
determine the real growth of investments. This allows investors to understand how much
value was preserved or lost in terms of purchasing power.
• Purpose: By working with inflation-adjusted prices, investors can make more informed
decisions about the true profitability of their investments.
2. Currency Conversion in Global Trading
• Scenario: You might be managing an international portfolio where stock prices are in
different currencies. If inflation rates differ across countries, adjusting stock prices for
inflation helps normalize data.
• Real-Time Use Case: Traders or financial analysts adjust stock prices in different currencies
by incorporating inflation factors from each country, which allows them to make fair
comparisons and determine which assets truly outperformed after adjusting for local
economic conditions.
3. Budgeting and Forecasting
• Scenario: Companies use historical data for financial forecasting. If you're working with
past sales figures, adjusting them for inflation ensures that the numbers are comparable to
today's environment.
• Real-Time Use Case: In corporate finance, when preparing budget forecasts or analyzing
long-term financial performance, inflation-adjusted stock prices are used to make more
accurate projections of future cash flows, profits, or investment returns.
4. Retirement Planning
• Scenario: In retirement planning, individuals often adjust future stock prices or asset values
for expected inflation to understand how much wealth they need to accumulate to maintain
their current lifestyle in the future.
• Real-Time Use Case: Financial planners use inflation-adjusted prices to calculate the future
value of assets and create more realistic savings targets. It helps clients determine how
much their stock investments will be worth after adjusting for inflation during retirement.
5. Valuing Companies or Projects
• Scenario: When valuing a company or an asset, you need to account for inflation to
understand its true financial health. Simply looking at nominal stock prices or profits can be
misleading.
• Real-Time Use Case: Investors and analysts often adjust historical financial data, including
stock prices and profits, for inflation to perform discounted cash flow (DCF) analyses. This
helps in determining the intrinsic value of a company and making better investment
decisions.
6. Comparing Historical Stock Prices
• Scenario: Comparing stock prices from different time periods can be distorted by inflation.
A stock that was worth $100 in 2000 may not have the same purchasing power today due to
inflation.
• Real-Time Use Case: Adjusting stock prices for inflation allows investors and analysts to
make fair historical comparisons across different time periods, which can reveal long-term
trends and help evaluate the performance of different investment strategies.
7. Economics and Policy Analysis
• Scenario: In policy-making or economic research, comparing financial data over long
periods can show the effect of inflation on wealth distribution or economic growth.
• Real-Time Use Case: Governments, economists, and financial institutions use inflation-
adjusted stock prices to assess the real impact of monetary policies or other economic
changes over time.
Chapter 7: Mathematical Functions
NumPy provides a wide range of mathematical functions that operate on arrays. These include
aggregation functions and mathematical operations that apply to each element in an array.

Aggregation Functions
Aggregation functions perform calculations such as sum, product, mean, minimum, and maximum
on the elements of arrays.

Example: Calculating Sum


python
Copy code
arr = np.array([1, 2, 3, 4])
sum_arr = np.sum(arr)
print(sum_arr) # Output: 10

Example: Calculating Mean


python
Copy code
arr = np.array([1, 2, 3, 4])
mean_arr = np.mean(arr)
print(mean_arr) # Output: 2.5

Example: Minimum and Maximum


python
Copy code
arr = np.array([1, 2, 3, 4])
print(np.min(arr)) # Output: 1
print(np.max(arr)) # Output: 4

Matrix Operations
NumPy supports matrix operations such as dot product and cross product.

Example: Dot Product


python
Copy code
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
dot_product = np.dot(arr1, arr2)
print(dot_product)
# Output:
# [[19 22]
# [43 50]]

Real-Time Use Case:


In sales analysis, you may want to combine sales data from different quarters into a single array for
year-end analysis.
Practical Example:
import numpy as np

# Sales data for two regions over three quarters


region1_sales = np.array([1000, 1200, 1100])
region2_sales = np.array([900, 1000, 1050])

# Stacking sales data horizontally (for analysis)


total_sales = np.hstack((region1_sales.reshape(-1, 1), region2_sales.reshape(-1,
1)))
print("Total sales for both regions:\n", total_sales)
Chapter 8: Random Number Generation
NumPy comes with the ability to generate random numbers, which is often used in simulations, data
generation, and probabilistic models.

Generating Random Numbers


The random() module in NumPy generates random values in various ways.

Example: Generating Random Numbers


python
Copy code
random_arr = np.random.random((2, 3))
print(random_arr)
# Output:
# [[0.1234 0.5678 0.9101]
# [0.3456 0.7890 0.1121]]

Random Distributions
NumPy also allows generating numbers based on statistical distributions.

Example: Generating Random Integers


python
Copy code
random_ints = np.random.randint(0, 10, size=(3, 3))
print(random_ints)
# Output (Example):
# [[2 8 1]
# [7 4 5]
# [9 0 3]]

Setting Random Seed


Setting a seed ensures reproducibility of results.

Example: Setting Seed


python
Copy code
np.random.seed(42)
random_arr = np.random.rand(3)
print(random_arr)
# Output: [0.37454012 0.95071431 0.73199394]

Use Case: Simulating Product Demand Forecast

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.

Example: Matrix Multiplication


python
Copy code
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
result = np.matmul(arr1, arr2)
print(result)
# Output:
# [[19 22]
# [43 50]]

Determinant of a Matrix
The determinant of a matrix can be computed using np.linalg.det().

Example: Calculating the Determinant


arr = np.array([[1, 2], [3, 4]])
determinant = np.linalg.det(arr)
print(determinant) # Output: -2.0

Use Case: Robotics - Path Planning

In robotics, matrix multiplication can be used to compute transformations for moving a robotic arm.
Example: Matrix Multiplication

# Matrices representing transformations for a robotic arm


arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
result = np.matmul(arr1, arr2)
print(result)
# Output:
# [[19 22]
# [43 50]]

This matrix multiplication helps in combining multiple transformation operations.

Use Case: Engineering - Stability of Structures


Calculating the determinant of a matrix can determine whether a system is stable, such as when
designing bridges or buildings.
Example: Determinant of a Matrix
# Matrix representing a system of forces in a structure
arr = np.array([[1, 2], [3, 4]])
determinant = np.linalg.det(arr)
print(determinant) # Output: -2.0

A non-zero determinant indicates that the structure is stable.


Chapter 10: Advanced Array Indexing and Slicing
Indexing and slicing are crucial for accessing and modifying elements within arrays efficiently.

Fancy Indexing
Fancy indexing refers to indexing using arrays of indices, allowing for complex selections.

Example: Using Fancy Indexing

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.

Example: Using Boolean Arrays for Selection

arr = np.array([1, 2, 3, 4, 5])


mask = arr > 2 # Creating a boolean mask
filtered_arr = arr[mask]
print(filtered_arr) # Output: [3 4 5]

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

# Image matrix representing pixel intensities


arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
# Select specific pixel groups
indices = np.array([[0, 1], [1, 2]])
selected_elements = arr[indices]
print(selected_elements)
# Output:
# [[10 20]
# [50 60]]

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

arr = np.array([1, 2, 3, 4, 5]) # Customer purchases in thousands


mask = arr > 2 # Customers who made purchases over 2k
filtered_arr = arr[mask]
print(filtered_arr) # Output: [3 4 5]

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

Case Study 5: Healthcare - Patient Data Analysis

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

# Simulated blood pressure readings before and after treatment


before_treatment = np.array([130, 135, 140, 145, 150])
after_treatment = np.array([120, 125, 130, 135, 130])

# Calculate the mean reduction in blood pressure


mean_reduction = np.mean(before_treatment - after_treatment)
print(f"Mean Reduction in Blood Pressure: {mean_reduction:.2f} mmHg")

Insights
By evaluating patient metrics, healthcare providers can assess treatment effectiveness and make
data-driven decisions for improving patient care.

You might also like