0% found this document useful (0 votes)
5 views17 pages

NumPy - The Super Toolbox For Numbers in Python

NumPy, short for Numerical Python, is a powerful Python library designed for efficient numerical computations, particularly with large datasets and arrays. It offers significant advantages over traditional Python lists, including speed, multi-dimensional support, and built-in statistical functions, while also having limitations such as requiring uniform data types. Installation is straightforward, and the library provides a wide range of functions for creating, manipulating, and performing operations on arrays.

Uploaded by

free gift's
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)
5 views17 pages

NumPy - The Super Toolbox For Numbers in Python

NumPy, short for Numerical Python, is a powerful Python library designed for efficient numerical computations, particularly with large datasets and arrays. It offers significant advantages over traditional Python lists, including speed, multi-dimensional support, and built-in statistical functions, while also having limitations such as requiring uniform data types. Installation is straightforward, and the library provides a wide range of functions for creating, manipulating, and performing operations on arrays.

Uploaded by

free gift's
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/ 17

NUMPY

The super Toolbox for numbers in Python

What is NumPy?
NumPy stands for "Numerical Python".

It is a Python library that helps us work with numbers, especially when


we deal with:

●​ Large amounts of data​

●​ Calculations​

●​ Arrays (like lists, but more powerful)​

Think of NumPy as your scientific calculator, but 100x smarter — and inside
your code!

Why Do We Need NumPy?


Let’s say you're a data analyst. You get a list of sales for 1,000 products.
You want to:

●​ Add 10% tax to all​

●​ Find out total sales​

●​ Filter only products with sales above ₹10,000​

Can you do that with Python lists? Yes, but you’ll write loops and slow
code.
With NumPy, you do it in one line, and it runs 100x faster. That’s why data
scientists and analysts love it.

Why NumPy Over Python Lists? (A Real-Life Analogy)


Imagine you’re packing lunch for 5 people.

●​ A Python list is like putting food into separate paper plates.​


You can eat from it, but it’s messy and slow to carry.​

●​ A NumPy array is like a compartment lunchbox.​


It’s clean, organized, stackable, and you can carry 100 boxes at once.​

Advantages of NumPy
Feature Why It's Useful

🚀 Speed Works faster than normal loops

🧠 Smarter Math You can add, multiply arrays directly

📦 Multi-dimensional Supports 1D, 2D, even 3D arrays

📉 Built-in stats Get mean, sum, std, etc., easily

🔁 Broadcasting You can add/multiply a single value to all items easily

💾 Memory Efficient Uses less memory than lists


Limitations of NumPy
Limitation What It Means

Same data type only You can't mix numbers and strings

No labels (like Pandas) No column names or row labels

Not for text Best only for number-based data

Needs extra libraries For real-world tasks, you’ll also use Pandas or Matplotlib

How to Install NumPy?


Simple one-time setup:

pip install numpy

Or if you're using Anaconda:

conda install numpy

Then in Python:

import numpy as np

We use np as a nickname, so we don’t have to write numpy every time.

NumPy Function Matrix

💪
We’re not going to learn “a few” functions.​
We're going to master NumPy step-by-step like legends

Here’s your Matrix Table:​


Divided by Difficulty and grouped by Use-Case.
🟢 Beginner – Must Learn First (Foundation Level)
Category Function(s) Use/Example

Create Arrays np.array() Create basic NumPy array


from list

np.arange() Create number range like


range()

np.linspace() Create evenly spaced numbers

Structure Info ndim, shape, size, dtype Understand shape, size, type
of array

Array with values np.zeros(), np.ones(), Predefined arrays


np.full()

Indexing/Slicing a[1], a[1:4], a[-1] Pick specific elements

Basic Operations +, -, *, /, ** Element-wise math

Aggregate sum(), mean(), max(), Stats on data


min(), std()

Broadcasting arr + 5, arr * 2 Apply a value to all elements

Random Values np.random.rand(), randint() Generate random values

🟡 Intermediate – Build Deeper Skills


Category Function(s) Use/Example

Shape change reshape(), flatten() Convert between 1D, 2D arrays

Stacking vstack(), hstack() Combine arrays


vertically/horizontally

Splitting split(), array_split() Divide one array into parts


Joining np.concatenate() Merges two arrays just like a
list

Conditional ops np.where(), np.clip() Replace/filter values based on


condition

Logical np.any(), np.all() Check if any/all conditions are


True

Sort & Unique np.sort(), np.unique() Clean up data, find unique


values

Math ops np.abs(), np.sqrt(), Scientific calculations


np.log(), np.exp()

🔴 Advanced – Rare but Useful


Category Function(s) Use/Example

Insert/Delete np.insert(), np.delete() Modify array contents

Tiling np.tile(), np.repeat() Duplicate data

Set ops np.intersect1d(), Set math


np.setdiff1d()

Missing Values np.isnan(), nan_to_num() Handle null or missing values

Matrix algebra np.dot(), np.transpose() Math for ML & linear algebra

Array Operations vs Array Functions in NumPy

1. Array Operations (What You Do to Arrays)

These are like actions or calculations you perform ON arrays.

Examples:
●​ Adding arrays: a + b​

●​ Multiply every element by 10: a * 10​

●​ Subtract one array from another

✅ These are mostly:


●​ Element-by-element operations​

●​ Math or logic-based​

●​ Super fast (no loops)

2. Array Functions (What You Ask From Arrays)

These are built-in tools to get information FROM an array or


transform it.

Examples:

●​ a.sum() → total of all elements​

●​ a.mean() → average​

●​ a.reshape(2, 3) → changes the shape

✅ These are:
●​ Built-in NumPy functions (either np.function() or array.function())​

●​ Often return new arrays or single values​

●​ Used for info, stats, or shape control


Think of it Like This:

Concept Action Type Real-Life Analogy

Array Operation Do something You paint each wall of a house

Array Function Ask something You measure the height of the walls

NumPy Foundations – Creating Arrays

Why Start with Arrays?

Everything in NumPy is built around arrays.

Think of an array as a grid of numbers.

●​ 1 row → 1D array (like a line of students)​

●​ Rows and columns → 2D array (like students sitting in rows)​

●​ Multiple rooms → 3D array (like classrooms in a school building)​

How to Create a NumPy Array?

import numpy as np

We always use np instead of writing numpy again and again. Just


like calling your friend “Bro” instead of their full name.

Method 1: Convert a Python list into a NumPy array

arr = np.array([10, 20, 30])


print(arr)

Output:

[10 20 30]

Fun Fact: A NumPy array doesn’t use commas inside – it’s tight and clean.​
It’s like a military parade – everyone stands aligned.

Method 2: Create a 2D Array (Matrix)

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


print(matrix)

Output:

[[1 2 3]
[4 5 6]]

Now you’ve made a matrix – like rows and columns in Excel.

Array Attributes – Know Your Array’s Shape and Size

Just like a person has height, weight, and age… arrays also have properties.

Here’s how to check them:

arr = np.array([[10, 20], [30, 40]])

print(arr.ndim) # Number of dimensions (2D)


print(arr.shape) # Shape → (rows, columns)
print(arr.size) # Total number of elements
print(arr.dtype) # Data type of elements
Practice Time – Quick Questions

Let your students try these 👇


1.​ Create a 1D array with values 5, 10, 15, 20​

2.​ Create a 2D array with values from 1 to 6 arranged in 2 rows​

3.​ Print the number of dimensions of the above array​

4.​ Print the shape and data type​

5.​ Change this list to an array: [3.5, 6.2, 1.0, 8.9]​

One-Liner Arrays – Pre-filled with Zeros, Ones, or Any Value

Zeros
np.zeros(5)
# [0. 0. 0. 0. 0.]

Ones
np.ones((2, 3))
# [[1. 1. 1.]
# [1. 1. 1.]]

Fill with custom value


np.full((3, 2), 99)
# [[99 99]
# [99 99]
# [99 99]]

It’s like placing empty chairs (zeros), filled chairs (ones), or VIP seats (custom
value) for guests at an event.

Final Thoughts for This Topic

Arrays are the heart of NumPy.If you understand how to create and
shape arrays, you’re already 25% ahead in Data Analysis.

1. np.arange() – The Number Line Generator


Think of it like a robot drawing a number line on the floor for you.

np.arange(1, 10)
# [1 2 3 4 5 6 7 8 9]

It starts at 1, ends before 10.

np.arange(1, 20, 2)
# [1 3 5 7 9 11 13 15 17 19]

Starts at 1, ends before 20, jumps by 2.

2. np.linspace() – Equally Spaced Points


Think of this as placing pebbles evenly between two poles.

np.linspace(0, 1, 5)
# [0. 0.25 0.5 0.75 1. ]
From 0 to 1, give me 5 values evenly spaced.

3. Indexing & Slicing – Like Cutting a Cake 🎂


arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # First slice
print(arr[-1]) # Last slice
print(arr[1:4]) # 20 to 40
print(arr[::2]) # Every second item

With 2D arrays:

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


print(mat[1]) # [3 4]
print(mat[1, 0]) # 3

It’s just like picking items off a food tray: row and column style.

4. Basic Operations – Calculator on Steroids 🧮


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

print(a + b) # [5 7 9]
print(a * b) # [4 10 18]
print(a ** 2) # [1 4 9]
print(a + 10) # [11 12 13]

No need for loops — NumPy handles math for entire arrays at once.
5. Aggregate Functions – Get the Big Picture 📊
a = np.array([10, 20, 30, 40])

print(a.sum()) # 100
print(a.mean()) # 25.0
print(a.min()) # 10
print(a.max()) # 40
print(a.std()) # 11.18...

Use this to get stats from your data in one line — like a mini Excel formula
engine.

6. Broadcasting – Smart Copy-Pasting 🧠


a = np.array([10, 20, 30])
print(a + 5)
# [15 25 35]

NumPy is smart. If you say “Add 5 to all,” it automatically copies and


adds without loops.

With 2D:

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


print(mat + 10)

Adds 10 to every element. No need to worry about shape if the logic fits.
7. Random Value Generators – Controlled Chaos 🎲
np.random.seed(42) # For repeatable output
np.random.rand(3) # 3 random floats (0 to 1)
np.random.randint(1, 10, 5) # 5 random ints between 1–9
np.random.randn(4) # Random floats from normal distribution

Great for simulations, practice datasets, testing models.

🎯 Bonus: Quick Challenges


1.​ Create an array with numbers from 5 to 45 skipping by 5​

2.​ Create a 1D array of 10 random integers between 50–100​

3.​ Take a 2D array and print the 2nd column​

4.​ Multiply all elements in [10, 20, 30] by 3 using broadcasting​

5.​ Use sum() and mean() on [100, 200, 300]​

Final Motivation
“You don’t need to know 1000 things in NumPy. You just need to
know the right 60 and use them like a ninja.”
INTERMEDIATE FUNCTIONS:
Just like LEGO blocks 🧱
– NumPy lets you reshape, stack, or flatten
arrays however you want!

1. reshape() – Reorganizing the Bricks

Imagine you have 6 bricks in one line:

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

Now you want to make 2 rows & 3 columns – like a table.

a.reshape(2, 3)

# [[1 2 3]
# [4 5 6]]

Or 3 rows & 2 columns:

a.reshape(3, 2)
# [[1 2]
# [3 4]
# [5 6]]

📌 Rule: The total number of elements must match. (You can’t reshape 6 items
into a 7-item shape.)

2. flatten() – Turning Table into a Single Line

If you have a 2D array like this:

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


And want to make it 1D again (like a string of pearls):

a.flatten()
# Output: [1 2 3 4 5 6]

📌 Think of this as folding your bedsheet into one straight line 🛏️


3. ravel() – Similar to flatten()

a.ravel()

Difference:

●​ flatten() gives you a copy​

●​ ravel() gives a view (faster, but changes affect original sometimes)​

Use flatten() if you're unsure — it's safer for beginners.

4. vstack() – Stack Vertically (Row-wise)

Stack two arrays on top of each other like pancakes 🥞:


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

np.vstack((a, b))
# Output:
# [[1 2 3]
# [4 5 6]]
5. hstack() – Stack Horizontally (Column-wise)

Put them side by side like books on a shelf 📚:


np.hstack((a, b))
# Output: [1 2 3 4 5 6]

6. split() and array_split() – Slicing Arrays into Chunks

Split a single array into parts:

a = np.array([10, 20, 30, 40, 50, 60])

np.split(a, 3)
# Output: [array([10, 20]), array([30, 40]), array([50, 60])]

If sizes don’t divide evenly, use array_split():

np.array_split(a, 4)
# Output: [array([10, 20]), array([30, 40]), array([50]), array([60])]

✅ Real-Life Analogy Summary


Operation What It Feels Like

reshape() Folding/unfolding clothes into rows/columns

flatten() Rolling up a carpet into a single line

vstack() Stacking chairs vertically

hstack() Arranging books side-by-side

split() Cutting a chocolate bar into pieces 🍫


🎯 Practice Time
1.​ Create an array of numbers from 1 to 12 and reshape into 3x4​

2.​ Convert a 2D array [[1, 2], [3, 4]] into 1D​

3.​ Stack [10, 20, 30], [40, 50, 60], and [70, 80, 90] vertically​

4.​ Stack the same arrays horizontally​

5.​ Split array [10, 20, 30, 40, 50, 60] into 3 equal parts​

🔥 Motivation:
"The more shapes your data takes, the more control you have over
your logic."

You might also like