What is NumPy?
NumPy stands for Numerical Python. It is one of the most important Python libraries for numerical computing and working with large amounts of data.
NumPy provides a powerful ndarray object that allows you to store and process collections of numbers efficiently. It also provides functions for mathematical calculations, statistics, linear algebra, random numbers, and data manipulation.
Fast Arrays
NumPy arrays are optimized for numerical operations and are generally faster than normal Python lists for large numerical datasets.
Vectorized Operations
You can perform calculations on entire arrays without writing explicit loops for every element.
Mathematical Functions
NumPy includes functions for statistics, trigonometry, logarithms, aggregation, and many other calculations.
Data Science Foundation
NumPy is widely used as a foundation for libraries such as Pandas, SciPy, and many machine-learning tools.
NumPy can be installed using pip.
pip install numpy
If you are using Jupyter Notebook, you can install it using:
!pip install numpy
The standard convention is to import NumPy using the alias np.
import numpy as np
numbers = np.array([10, 20, 30, 40, 50])
print(numbers)
np is only an alias.
You can technically choose another name, but np
is the commonly used convention.
The np.array() function converts a Python list
or other sequence into a NumPy array.
import numpy as np
numbers = np.array([10, 20, 30, 40, 50])
print(numbers)
Real-Time Example: Product Prices
import numpy as np
prices = np.array([499, 799, 1299, 999, 1499])
print("Product prices:", prices)
Python lists and NumPy arrays can both store collections of values, but NumPy arrays are specifically optimized for numerical computing.
| Feature | Python List | NumPy Array |
|---|---|---|
| Purpose | General-purpose collection | Numerical computing |
| Performance | Good for general operations | Optimized for numerical operations |
| Mathematical operations | Often require loops | Can use vectorized operations |
| Multidimensional data | Nested lists | Native multidimensional arrays |
Example
import numpy as np
list_numbers = [10, 20, 30]
array_numbers = np.array([10, 20, 30])
print(array_numbers * 2)
NumPy arrays store values using a specific data type.
You can check the type using dtype.
import numpy as np
numbers = np.array([10, 20, 30])
print(numbers.dtype)
Specifying a Data Type
import numpy as np
numbers = np.array([10, 20, 30], dtype=float)
print(numbers)
print(numbers.dtype)
NumPy supports one-dimensional, two-dimensional, and higher-dimensional arrays.
One-Dimensional Array
import numpy as np
numbers = np.array([10, 20, 30, 40])
print(numbers)
Two-Dimensional Array
import numpy as np
matrix = np.array([
[10, 20, 30],
[40, 50, 60]
])
print(matrix)
Checking Dimensions
print(matrix.ndim)
NumPy provides useful properties to understand the structure of 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)
shape tells you the size of each dimension, while size gives the total number of elements.
NumPy uses zero-based indexing, just like Python lists.
import numpy as np
numbers = np.array([10, 20, 30, 40, 50])
print(numbers[0])
print(numbers[2])
print(numbers[-1])
Real-Time Example: Employee Salaries
import numpy as np
salaries = np.array([35000, 42000, 50000, 60000, 75000])
print("First employee salary:", salaries[0])
print("Highest listed salary:", salaries[-1])
Slicing allows you to extract a portion of an array.
import numpy as np
numbers = np.array([10, 20, 30, 40, 50])
print(numbers[1:4])
print(numbers[:3])
print(numbers[2:])
Real-Time Example: Sales Records
import numpy as np
sales = np.array([12000, 15000, 18000, 21000, 25000])
recent_sales = sales[-3:]
print("Recent sales:", recent_sales)
NumPy allows you to perform arithmetic operations directly on arrays.
import numpy as np
prices = np.array([100, 200, 300])
print("Add:", prices + 50)
print("Subtract:", prices - 20)
print("Multiply:", prices * 2)
print("Divide:", prices / 2)
Suppose an online store wants to apply a 10% discount to multiple products. NumPy can perform the calculation on the entire array.
import numpy as np
prices = np.array([1000, 1500, 2000, 2500])
discount = prices * 0.10
final_prices = prices - discount
print("Original prices:", prices)
print("Discount:", discount)
print("Final prices:", final_prices)
NumPy provides many mathematical functions that can operate directly on arrays.
import numpy as np
numbers = np.array([1, 4, 9, 16, 25])
print("Square roots:", np.sqrt(numbers))
print("Squares:", np.square(numbers))
print("Maximum:", np.max(numbers))
print("Minimum:", np.min(numbers))
NumPy provides aggregation functions that are extremely useful when analyzing data.
import numpy as np
sales = np.array([100, 200, 300, 400, 500])
print("Total:", np.sum(sales))
print("Average:", np.mean(sales))
print("Minimum:", np.min(sales))
print("Maximum:", np.max(sales))
Real-Time Example: Monthly Sales
import numpy as np
monthly_sales = np.array([
45000, 52000, 48000, 61000,
57000, 68000, 72000, 65000
])
print("Total sales:", np.sum(monthly_sales))
print("Average sales:", np.mean(monthly_sales))
print("Highest sales:", np.max(monthly_sales))
print("Lowest sales:", np.min(monthly_sales))
Standard deviation measures how spread out values are from the average.
import numpy as np
scores = np.array([70, 72, 75, 80, 85, 90])
print("Average:", np.mean(scores))
print("Standard deviation:", np.std(scores))
This can be useful for analyzing exam scores, sales variations, production measurements, and other datasets.
NumPy provides convenient functions for creating arrays filled with zeros or ones.
import numpy as np
zeros = np.zeros(5)
ones = np.ones(5)
print("Zeros:", zeros)
print("Ones:", ones)
Creating a Matrix
matrix = np.zeros((3, 4))
print(matrix)
np.arange() creates evenly spaced values
within a specified range.
import numpy as np
numbers = np.arange(1, 11)
print(numbers)
Using a Step
numbers = np.arange(0, 21, 5)
print(numbers)
np.linspace() generates a specified number
of evenly spaced values between two endpoints.
import numpy as np
values = np.linspace(0, 100, 6)
print(values)
This is useful when generating measurement intervals, plotting data, simulations, and scientific calculations.
The reshape() method changes the structure
of an array without changing its data.
import numpy as np
numbers = np.arange(1, 13)
matrix = numbers.reshape(3, 4)
print(matrix)
You can convert a multidimensional array into a
one-dimensional array using flatten().
import numpy as np
matrix = np.array([
[10, 20, 30],
[40, 50, 60]
])
flat = matrix.flatten()
print(flat)
Two-dimensional arrays are useful for representing tables, matrices, images, spreadsheets, and other structured data.
import numpy as np
marks = np.array([
[80, 75, 90],
[65, 85, 70],
[90, 95, 88]
])
print("First student:", marks[0])
print("First student's first mark:", marks[0, 0])
print("Second student's third mark:", marks[1, 2])
Real-Time Example: Student Marks
import numpy as np
marks = np.array([
[80, 75, 90],
[65, 85, 70],
[90, 95, 88]
])
student_average = np.mean(marks, axis=1)
print("Student averages:", student_average)
The axis argument tells NumPy which direction
an operation should work along.
import numpy as np
marks = np.array([
[80, 70, 90],
[60, 75, 85],
[90, 95, 88]
])
print("Column averages:", np.mean(marks, axis=0))
print("Row averages:", np.mean(marks, axis=1))
axis=0
works down the rows, while axis=1 works across
the columns of each row.
NumPy can filter array elements using conditions.
import numpy as np
prices = np.array([500, 1200, 800, 2000, 1500])
expensive = prices > 1000
print(expensive)
print(prices[expensive])
Real-Time Example: High-Value Orders
import numpy as np
orders = np.array([
450, 1250, 780, 2300, 950, 1800
])
high_value_orders = orders[orders > 1000]
print("High-value orders:", high_value_orders)
NumPy provides random-number generation tools that are useful for simulations, testing, sampling, and modeling.
import numpy as np
numbers = np.random.randint(1, 101, 5)
print(numbers)
The output changes because the numbers are randomly generated.
Real-Time Example: Simulating Daily Customers
import numpy as np
customers = np.random.randint(50, 201, 7)
print("Customers for 7 days:", customers)
print("Average customers:", np.mean(customers))
Use np.sort() to sort array values.
import numpy as np
scores = np.array([75, 92, 68, 88, 95, 70])
sorted_scores = np.sort(scores)
print("Sorted scores:", sorted_scores)
Descending Order
descending = np.sort(scores)[::-1]
print(descending)
NumPy can combine multiple arrays using
np.concatenate().
import numpy as np
morning_sales = np.array([100, 200, 300])
evening_sales = np.array([400, 500, 600])
all_sales = np.concatenate((morning_sales, evening_sales))
print(all_sales)
Imagine a company wants to analyze employee salaries. NumPy can calculate the total, average, minimum, maximum, and salaries above a particular threshold.
import numpy as np
salaries = np.array([
30000,
42000,
55000,
48000,
72000,
65000
])
print("Total salary:", np.sum(salaries))
print("Average salary:", np.mean(salaries))
print("Minimum salary:", np.min(salaries))
print("Maximum salary:", np.max(salaries))
high_salary = salaries[salaries > 50000]
print("Salaries above 50000:", high_salary)
NumPy can be used to analyze temperature measurements collected during a week.
import numpy as np
temperatures = np.array([
31.5, 32.2, 30.8, 33.1,
34.5, 35.2, 32.8
])
print("Average temperature:", np.mean(temperatures))
print("Highest temperature:", np.max(temperatures))
print("Lowest temperature:", np.min(temperatures))
hot_days = temperatures[temperatures > 33]
print("Hot days:", hot_days)
A school can use NumPy to calculate student averages and identify students who scored above a threshold.
import numpy as np
marks = np.array([
78, 85, 92, 67, 88,
95, 72, 81, 90, 76
])
average = np.mean(marks)
highest = np.max(marks)
lowest = np.min(marks)
passed = marks[marks >= 40]
high_performers = marks[marks >= 80]
print("Average:", average)
print("Highest:", highest)
print("Lowest:", lowest)
print("Number passed:", len(passed))
print("High performers:", high_performers)
An inventory system can use NumPy arrays to identify products that need restocking.
import numpy as np
stock = np.array([50, 8, 25, 3, 45, 6, 70])
low_stock = stock[stock < 10]
print("Current stock:", stock)
print("Low-stock products:", low_stock)
print("Number of products needing restock:", len(low_stock))
The following example shows how NumPy can process sales data for a simple business dashboard.
import numpy as np
sales = np.array([
12000, 15000, 18000, 14000,
22000, 25000, 21000, 19000,
28000, 30000, 27000, 32000
])
total_sales = np.sum(sales)
average_sales = np.mean(sales)
highest_sales = np.max(sales)
lowest_sales = np.min(sales)
above_average = sales[sales > average_sales]
print("Total yearly sales:", total_sales)
print("Average monthly sales:", average_sales)
print("Highest monthly sales:", highest_sales)
print("Lowest monthly sales:", lowest_sales)
print("Months above average:", above_average)
NumPy can perform matrix calculations, which are important in engineering, data science, machine learning, and scientific computing.
import numpy as np
a = np.array([
[1, 2],
[3, 4]
])
b = np.array([
[5, 6],
[7, 8]
])
result = a + b
print(result)
Matrix Multiplication
result = a @ b
print(result)
Use copy() when you need an independent copy
of an array.
import numpy as np
original = np.array([10, 20, 30])
copied = original.copy()
copied[0] = 100
print("Original:", original)
print("Copied:", copied)
copy() creates a separate array.
| Function | Purpose |
|---|---|
np.array() |
Create a NumPy array |
np.zeros() |
Create an array filled with zeros |
np.ones() |
Create an array filled with ones |
np.arange() |
Create evenly spaced integer values |
np.linspace() |
Create evenly spaced values |
np.sum() |
Calculate total |
np.mean() |
Calculate average |
np.min() |
Find minimum value |
np.max() |
Find maximum value |
np.std() |
Calculate standard deviation |
np.sort() |
Sort array values |
np.concatenate() |
Join arrays |
np.reshape() |
Change array shape |
np.sqrt() |
Calculate square roots |
NumPy is especially useful when your application performs a large number of numerical calculations.
- Working with large numerical datasets
- Performing mathematical calculations
- Processing matrices and multidimensional data
- Statistical analysis
- Scientific computing
- Machine-learning data preparation
- Simulation and numerical modeling
- Image and signal processing
- Install NumPy using
pip install numpy. - Usually import NumPy as
import numpy as np. - Use
np.array()to create NumPy arrays. - NumPy arrays use zero-based indexing.
- Use
shapeto understand array dimensions. - Use
ndimto find the number of dimensions. - Use
sizeto find the total number of elements. - Use vectorized operations instead of unnecessary Python loops.
- Use
axiswhen performing operations on specific dimensions. - Use boolean indexing to filter data efficiently.
- Use
reshape()when you need to change array structure. - Use
copy()when you need an independent array copy. - NumPy is especially valuable for numerical and scientific workloads.
Here is a complete example combining array creation, calculations, filtering, and statistics.
import numpy as np
# Monthly revenue
revenue = np.array([
45000, 52000, 48000, 61000,
57000, 68000, 72000, 65000,
75000, 81000, 79000, 90000
])
# Basic statistics
total = np.sum(revenue)
average = np.mean(revenue)
highest = np.max(revenue)
lowest = np.min(revenue)
# Above-average months
above_average = revenue[revenue > average]
# Apply 5% growth
projected_revenue = revenue * 1.05
print("Total revenue:", total)
print("Average revenue:", average)
print("Highest revenue:", highest)
print("Lowest revenue:", lowest)
print("Above-average revenue:", above_average)
print("Projected revenue:", projected_revenue)