Python NumPy
Learn NumPy, one of Python's most important libraries for numerical computing. You will work with arrays, indexing, slicing, reshaping, mathematical operations, broadcasting, statistics, filtering and practical data-analysis techniques.
Learning Objectives
NumPy provides powerful tools for working with numerical data. It is a foundation for many Python data-science, machine-learning and scientific-computing libraries.
You will learn how to:
- Understand what NumPy is and why it matters.
- Create and inspect NumPy arrays.
- Understand array dimensions and shapes.
- Access elements using indexing.
- Extract portions of arrays using slicing.
- Reshape and flatten arrays.
- Create arrays filled with zeros and ones.
- Generate numerical sequences.
- Generate random numerical data.
- Perform vectorized mathematical operations.
- Understand broadcasting.
- Calculate statistical values.
- Filter arrays using conditions.
- Sort and manipulate numerical data.
- Understand NumPy views and copies.
- Perform basic matrix operations.
What Is NumPy?
NumPy stands for Numerical Python. It is a fundamental Python library for numerical computing.
Its most important feature is the
ndarray, a multidimensional array designed
to store and process numerical data efficiently.
Python List
↓
General-purpose collection
NumPy Array
↓
Numerical data structure
↓
Fast mathematical operations
↓
Data Science / ML / Scientific Computing
Where NumPy Is Used
- Data analysis
- Machine learning
- Scientific computing
- Statistics
- Engineering
- Financial analysis
- Image processing
- Simulation
Why Use NumPy?
Python lists are flexible and extremely useful, but numerical operations over large datasets can often be expressed more efficiently with NumPy arrays.
numbers = [10, 20, 30, 40]
result = []
for number in numbers:
result.append(number * 2)
print(result)
With NumPy, the same operation can be expressed using vectorized array operations.
import numpy as np
numbers = np.array([10, 20, 30, 40])
result = numbers * 2
print(result)
Output
[20 40 60 80]
NumPy performs the operation across the entire array without requiring you to write an explicit Python loop.
Installing NumPy
Install NumPy using pip.
python -m pip install numpy
If you are working inside a virtual environment, make sure the environment is activated before installing the package.
python -m pip show numpy
This can be used to inspect the installed package.
Importing NumPy
NumPy is conventionally imported using the alias
np.
import numpy as np
numbers = np.array([10, 20, 30])
print(numbers)
Why np?
np is the widely used convention for
referring to NumPy throughout Python projects,
tutorials and data-science code.
NumPy Arrays
The central data structure in NumPy is the
ndarray.
import numpy as np
numbers = np.array([10, 20, 30, 40])
print(numbers)
Output
[10 20 30 40]
Unlike a regular Python list, a NumPy array is designed specifically for efficient numerical computation.
Creating Arrays
You can create arrays from Python lists and tuples.
import numpy as np
from_list = np.array(
[10, 20, 30]
)
from_tuple = np.array(
(40, 50, 60)
)
print(from_list)
print(from_tuple)
NumPy also supports multidimensional arrays.
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(matrix)
Output
[[1 2 3]
[4 5 6]]
Understanding Data Types
NumPy arrays have a data type called
dtype.
import numpy as np
numbers = np.array([
10,
20,
30
])
print(numbers.dtype)
You can explicitly request a data type.
numbers = np.array(
[10, 20, 30],
dtype=float
)
print(numbers)
Output
[10. 20. 30.]
NumPy supports many numerical types, including integer and floating-point types.
Understanding Dimensions
A NumPy array can have one or more dimensions.
import numpy as np
one_d = np.array(
[1, 2, 3]
)
two_d = np.array([
[1, 2, 3],
[4, 5, 6]
])
three_d = np.array([
[
[1, 2],
[3, 4]
]
])
print(one_d.ndim)
print(two_d.ndim)
print(three_d.ndim)
Output
1
2
3
ndim tells you how many dimensions the
array has.
Shape and Size
NumPy provides several properties for understanding an array.
import numpy as np
data = np.array([
[10, 20, 30],
[40, 50, 60]
])
print("Shape:", data.shape)
print("Size:", data.size)
print("Dimensions:", data.ndim)
Output
Shape: (2, 3)
Size: 6
Dimensions: 2
Remember
-
shapedescribes the structure. -
sizegives the total number of elements. -
ndimgives the number of dimensions.
Array Indexing
NumPy uses zero-based indexing, just like Python lists.
import numpy as np
numbers = np.array([
10, 20, 30, 40
])
print(numbers[0])
print(numbers[2])
print(numbers[-1])
Output
10
30
40
For two-dimensional arrays, provide an index for the row and column.
matrix = np.array([
[10, 20, 30],
[40, 50, 60]
])
print(matrix[0, 1])
print(matrix[1, 2])
Output
20
60
Array Slicing
Array slicing works similarly to Python list slicing.
import numpy as np
numbers = np.array([
10, 20, 30, 40, 50
])
print(numbers[1:4])
print(numbers[:3])
print(numbers[::2])
Output
[20 30 40]
[10 20 30]
[10 30 50]
Two-dimensional arrays can also be sliced.
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print(matrix[0:2, 1:3])
Output
[[2 3]
[5 6]]
Reshaping Arrays
reshape() changes the structure of an
array without changing its values.
import numpy as np
numbers = np.array([
1, 2, 3, 4, 5, 6
])
matrix = numbers.reshape(
2,
3
)
print(matrix)
Output
[[1 2 3]
[4 5 6]]
Important Rule
The new shape must contain the same total number of elements.
Six elements can become (2, 3),
(3, 2) or (6, 1), but not
(4, 2).
Flattening Arrays
Sometimes you need to convert a multidimensional array into one dimension.
import numpy as np
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
flat = matrix.flatten()
print(flat)
Output
[1 2 3 4 5 6]
flatten() returns a one-dimensional copy
of the array.
Creating Arrays with Zeros and Ones
NumPy provides convenient functions for creating arrays with predefined values.
import numpy as np
zeros = np.zeros(5)
ones = np.ones(5)
print(zeros)
print(ones)
Output
[0. 0. 0. 0. 0.]
[1. 1. 1. 1. 1.]
You can also create multidimensional arrays.
matrix = np.zeros(
(2, 3)
)
print(matrix)
arange() and linspace()
arange() generates evenly spaced values
based on a step.
import numpy as np
numbers = np.arange(
0,
10,
2
)
print(numbers)
Output
[0 2 4 6 8]
linspace() generates a specified number
of evenly spaced values between two endpoints.
values = np.linspace(
0,
1,
5
)
print(values)
Output
[0. 0.25 0.5 0.75 1. ]
Generating Random Numbers
NumPy includes a random-number generation system that is useful for simulations, testing and data science.
import numpy as np
numbers = np.random.rand(5)
print(numbers)
The values are random floating-point numbers between 0 and 1.
You can also generate random integers.
numbers = np.random.randint(
1,
101,
size=5
)
print(numbers)
Reproducible Randomness
When you need reproducible results, use a random generator with a fixed seed.
rng = np.random.default_rng(42)
numbers = rng.integers(
1,
101,
size=5
)
print(numbers)
Array Operations
NumPy allows mathematical operations to be applied directly to arrays.
import numpy as np
numbers = np.array([
10, 20, 30
])
print(numbers + 5)
print(numbers * 2)
print(numbers / 10)
print(numbers ** 2)
Output
[15 25 35]
[20 40 60]
[1. 2. 3.]
[100 400 900]
You can also perform element-by-element operations between arrays.
a = np.array([
10, 20, 30
])
b = np.array([
1, 2, 3
])
print(a + b)
print(a * b)
Output
[11 22 33]
[10 40 90]
Broadcasting
Broadcasting allows NumPy to perform operations between arrays of compatible shapes.
import numpy as np
prices = np.array([
100,
200,
300
])
tax_rate = 0.10
tax = prices * tax_rate
print(tax)
Output
[10. 20. 30.]
NumPy effectively applies the scalar value to every compatible element.
prices + 50
Here, 50 is broadcast across every price.
Aggregation Functions
NumPy provides functions for quickly summarizing numerical arrays.
import numpy as np
sales = np.array([
120,
250,
180,
300,
150
])
print("Total:", np.sum(sales))
print("Minimum:", np.min(sales))
print("Maximum:", np.max(sales))
print("Average:", np.mean(sales))
Output
Total: 1000
Minimum: 120
Maximum: 300
Average: 200.0
These functions are extremely useful when working with business and analytical datasets.
Statistical Functions
NumPy includes many functions for statistical analysis.
import numpy as np
scores = np.array([
70,
80,
85,
90,
95
])
print("Mean:", np.mean(scores))
print("Median:", np.median(scores))
print("Standard deviation:", np.std(scores))
print("Variance:", np.var(scores))
These calculations are frequently used in data analysis, machine learning and scientific computing.
Important Functions
np.mean()np.median()np.std()np.var()np.min()np.max()np.sum()
Filtering Arrays
Boolean conditions can be used to filter NumPy arrays.
import numpy as np
prices = np.array([
100,
500,
800,
1200,
300
])
expensive = prices > 500
print(expensive)
Output
[False False True True False]
Use the Boolean array to retrieve the matching values.
filtered = prices[
prices > 500
]
print(filtered)
Output
[ 800 1200]
This technique is called Boolean indexing.
Sorting Arrays
Use np.sort() to return sorted values.
import numpy as np
numbers = np.array([
50,
10,
40,
20,
30
])
sorted_numbers = np.sort(
numbers
)
print(sorted_numbers)
Output
[10 20 30 40 50]
You can also find the indexes that would sort an array
using argsort().
indexes = np.argsort(
numbers
)
print(indexes)
Copy vs View
One important NumPy concept is the difference between copying data and creating another view of the same data.
Copy
import numpy as np
original = np.array([
10,
20,
30
])
copy = original.copy()
copy[0] = 999
print(original)
print(copy)
Output
[10 20 30]
[999 20 30]
The copied array is independent of the original.
View
view = original.view()
view[0] = 500
print(original)
A view can share the underlying data with the original array. This distinction matters when modifying arrays.
Matrix Operations
NumPy can also perform common matrix operations.
import numpy as np
a = np.array([
[1, 2],
[3, 4]
])
b = np.array([
[5, 6],
[7, 8]
])
result = a @ b
print(result)
Output
[[19 22]
[43 50]]
The @ operator performs matrix
multiplication.
Do Not Confuse These
a * b
performs element-wise multiplication.
a @ b
performs matrix multiplication.
Practical Example — Sales Analysis
Let's use NumPy to analyze a small set of monthly sales.
import numpy as np
sales = np.array([
1200,
1500,
1100,
1800,
2100,
1900
])
print("Total sales:", np.sum(sales))
print("Average sales:", np.mean(sales))
print("Highest sales:", np.max(sales))
print("Lowest sales:", np.min(sales))
above_average = sales[
sales > np.mean(sales)
]
print(
"Above average:",
above_average
)
Expected Output
Total sales: 9600
Average sales: 1600.0
Highest sales: 2100
Lowest sales: 1100
Above average: [1800 2100 1900]
Notice how a few lines of NumPy can perform several useful analytical operations.
Raw Sales
↓
NumPy Array
↓
Aggregation
↓
Filtering
↓
Business Insight
Common NumPy Mistakes
Mistake 1 — Forgetting the Import
numbers = np.array([1, 2, 3])
This fails if NumPy has not been imported as
np.
Mistake 2 — Invalid Reshape
The total number of elements must remain the same when reshaping an array.
Mistake 3 — Confusing * and @
* performs element-wise multiplication,
while @ performs matrix multiplication.
Mistake 4 — Unexpected Modification
A view may share data with another array. Use
copy() when you need an independent
array.
Mistake 5 — Ignoring Shape
Many NumPy operations depend on compatible array
shapes. Always inspect shape when
debugging numerical code.
Practice Exercises
Exercise 1 — Create an Array
Create a NumPy array containing the numbers 10, 20, 30, 40 and 50.
Exercise 2 — Array Statistics
Create an array of student marks and calculate the total, average, minimum and maximum.
Exercise 3 — Filtering
Given an array of prices, return only products costing more than 1,000.
Exercise 4 — Reshape
Create an array containing numbers 1–12 and reshape it into a 3 × 4 matrix.
Exercise 5 — Random Data
Generate 20 random integers between 1 and 100 and calculate their average.
Exercise 6 — Sales Analysis
Create monthly sales data and find all months whose sales are greater than the annual average.
Mini Challenge — Ecommerce Sales Analyzer
Build a NumPy-based sales analyzer for an ecommerce business.
Your Mission
- Create a NumPy array containing daily sales.
- Calculate total sales.
- Calculate average daily sales.
- Find the highest sales day.
- Find the lowest sales day.
- Identify days above the average.
- Calculate a 10% tax amount for every sale.
- Calculate the final amount including tax.
- Sort the sales values.
Starter Code
import numpy as np
sales = np.array([
1200,
850,
1500,
2100,
950,
1750,
1300
])
average = np.mean(sales)
above_average = sales[
sales > average
]
tax = sales * 0.10
final_sales = sales + tax
print("Total:", np.sum(sales))
print("Average:", average)
print("Highest:", np.max(sales))
print("Lowest:", np.min(sales))
print(
"Above average:",
above_average
)
print(
"Final sales:",
final_sales
)
Advanced Extension
Extend the program to represent several products and several days using a two-dimensional NumPy array.
sales = np.array([
[1200, 1500, 1300],
[900, 1100, 1400],
[1700, 1800, 1600]
])
Then calculate totals by row and by column.
Think Like a Data Analyst
Try to solve the challenge with NumPy operations instead of manually writing loops. The goal is to become comfortable expressing numerical operations using arrays.
Knowledge Check
1. What does NumPy primarily provide?
2. What is the conventional NumPy alias?
3. What does ndim represent?
4. What does shape tell you?
5. Which function calculates an average?
6. What does reshape() do?
7. What is Boolean indexing useful for?
8. What does broadcasting allow?
9. What is the difference between * and @ for matrices?
10. Why might you use copy()?
Lesson Summary
NumPy is one of the most important foundations of the Python data-science ecosystem. Its array-based approach makes numerical operations concise, powerful and highly useful for analytical work.
What You Learned
- NumPy is designed for numerical computing.
-
NumPy's main data structure is the
ndarray. - Arrays can have one or multiple dimensions.
-
shape,sizeandndimdescribe arrays. - Arrays support indexing and slicing.
-
reshape()changes array structure. -
flatten()converts an array to one dimension. -
arange()andlinspace()generate numerical sequences. - NumPy supports random-number generation.
- Mathematical operations can be vectorized.
- Broadcasting enables operations with compatible shapes.
- Aggregation and statistical functions make analysis easier.
- Boolean indexing provides powerful filtering.
- Copies and views behave differently.
- NumPy supports important matrix operations.
In the next lesson, you will combine Python's data structures and NumPy concepts with one of the most important libraries for real-world tabular data: Pandas.
Ready to Continue?
You have completed the Python NumPy lesson.