Introduction to NumPy
A Powerful Library for Numerical
Computations in Python
What is NumPy?
• NumPy (Numerical Python) is a powerful
library for numerical computations.
• Used for handling multi-dimensional arrays
and performing high-speed mathematical
operations.
• Provides support for data science, machine
learning, and large dataset analysis.
Scenario Overview
• Astronomers track the moon’s visibility for the
last 10 days of the month.
• If the moon is visible on the 29th day, the
month will be 29 days; otherwise, 30 days.
• Objective: Use NumPy arrays to check the
29th day's visibility score.
NumPy Code for Moon Visibility
Calculation
Code
import numpy as np
visibility_scores = [Link]([0.1, 0.2, 0.15, 0.3, 0.4, 0.5, 0.6, 0.65,
0.75, 0.8])
if visibility_scores[8] >= 0.7:
print('Prediction: The month will have 29 days 🌙')
else:
print('Prediction: The month will have 30 days 🌕')
Why Use NumPy?
• Faster than Python lists.
• Uses less memory.
• Built-in mathematical and statistical functions.
• Supports large datasets efficiently.
import time
import numpy as np
# Python list
list1 = list(range(1000000))
list2 = list(range(1000000))
start = [Link]()
result = [x+y for x, y in zip(list1, list2)]
print("List time:", [Link]() - start)
# NumPy array
arr1 = [Link](1000000)
arr2 = [Link](1000000)
start = [Link]()
result = arr1 + arr2
print("NumPy time:", [Link]() - start)
Creating NumPy Arrays
• From Python lists: [Link]([1, 2, 3, 4, 5])
• Using built-in methods: [Link]((3,3)),
[Link]((2,2))
• Generating random numbers:
[Link](3,3),
[Link](1,100,(2,3))
Using Built-in Methods
• NumPy provides built-in functions to create
arrays quickly.
• Examples:
• [Link]((3,3)) # Creates a 3x3 array filled
with zeros
• [Link]((2,2)) # Creates a 2x2 array filled with
ones
Python Example: Image Processing
import numpy as np
import cv2
import os
import [Link] as plt
# ✅ Use absolute path
image_path = r"d:\Peak Solutions\Batch2\[Link]"
# ✅ Check if file exists
if not [Link](image_path):
print(f"❌ File not found at: {image_path}")
else:
# Load image in color
image = [Link](image_path, cv2.IMREAD_COLOR)
if image is None:
print("❌ Failed to load image. Check file format or corruption.")
else:
image_array = [Link](image)
print("✅ Image loaded successfully!")
print("Image Shape:", image_array.shape) # (Height, Width, 3)
# OpenCV loads images in BGR (Blue, Green, Red),
# but Matplotlib expects RGB → so convert before display
image_rgb = [Link](image_array, cv2.COLOR_BGR2RGB)
# ✅ Display color image
[Link](image_rgb)
[Link]("Color Image")
[Link]('off')
[Link]()
Python Example: Image Processing
import numpy as np
import cv2
import os
import [Link] as plt
# Load image
image_path = r"d:\Peak Solutions\Batch2\[Link]"
image = [Link](image_path, cv2.IMREAD_COLOR)
if image is None:
print("❌ Failed to load image. Check file path.")
else:
# Convert to RGB for matplotlib
img_rgb = [Link](image, cv2.COLOR_BGR2RGB)
# Brighten the image (add +50 to pixel values, clip to max 255)
brighter = [Link](img_rgb + 50, 0, 255).astype(np.uint8)
# Darken the image (subtract 50 from pixel values)
darker = [Link](img_rgb - 50, 0, 255).astype(np.uint8)
# Invert the image (like a photo negative)
inverted = 255 - img_rgb
# Extract only the Red channel
red_channel = img_rgb.copy()
red_channel[:, :, 1] = 0 # remove Green
red_channel[:, :, 2] = 0 # remove Blue
# Display results
fig, axs = [Link](1, 5, figsize=(18, 5))
axs[0].imshow(img_rgb); axs[0].set_title("Original"); axs[0].axis("off")
axs[1].imshow(brighter); axs[1].set_title("Brighter (+50)"); axs[1].axis("off")
axs[2].imshow(darker); axs[2].set_title("Darker (-50)"); axs[2].axis("off")
axs[3].imshow(inverted); axs[3].set_title("Inverted"); axs[3].axis("off")
axs[4].imshow(red_channel); axs[4].set_title("Red Channel Only"); axs[4].axis("off")
[Link]()
Array Attributes & Methods
• Reshaping: [Link](2,3)
• Finding Max/Min: [Link](), [Link]()
• Shape, dtype, size: [Link], [Link], [Link]
Operations on Arrays
• Copying: [Link]()
• Appending: [Link](arr, [4,5])
• Sorting: [Link](arr)
• Deleting: [Link](arr, index)
• Concatenation: [Link]((arr1, arr2))
• Splitting: [Link](arr,2)
Real-Life Applications of NumPy
• Data Science: Handling large datasets efficiently.
• Machine Learning: Used in TensorFlow & Scikit-
Learn.
• Image Processing: Manipulating images as
numerical arrays.
• Finance & Statistics: Analyzing stock market
trends.
• Scientific Computing: Used in physics, chemistry,
and engineering computations.
Python Example: Stock Market
Analysis
• import numpy as np
• stock_prices = [Link]([100, 102, 98, 105,
110])
• average_price = [Link](stock_prices)
• print('Average Stock Price:', average_price)
Conclusion
• NumPy is essential for numerical computing in
Python.
• It provides efficient array operations and is
widely used in AI & ML.
• Mastering NumPy unlocks advanced data
processing capabilities.