Python NumPy

Learn NumPy arrays, mathematical operations, indexing, statistics, reshaping, and real-time data-processing examples in Python.

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.

1. Installing NumPy

NumPy can be installed using pip.

Terminal
pip install numpy

If you are using Jupyter Notebook, you can install it using:

Jupyter Notebook
!pip install numpy
2. Importing NumPy

The standard convention is to import NumPy using the alias np.

Python
import numpy as np

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

print(numbers)
[10 20 30 40 50]
Note: np is only an alias. You can technically choose another name, but np is the commonly used convention.
3. Creating a NumPy Array

The np.array() function converts a Python list or other sequence into a NumPy array.

Basic Array
import numpy as np

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

print(numbers)
[10 20 30 40 50]

Real-Time Example: Product Prices

Product Prices
import numpy as np

prices = np.array([499, 799, 1299, 999, 1499])

print("Product prices:", prices)
Product prices: [ 499 799 1299 999 1499]
4. NumPy Array vs Python List

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

List vs NumPy
import numpy as np

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

print(array_numbers * 2)
[20 40 60]
5. NumPy Data Types

NumPy arrays store values using a specific data type. You can check the type using dtype.

Checking dtype
import numpy as np

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

print(numbers.dtype)
int64

Specifying a Data Type

float Array
import numpy as np

numbers = np.array([10, 20, 30], dtype=float)

print(numbers)
print(numbers.dtype)
[10. 20. 30.] float64
6. Array Dimensions

NumPy supports one-dimensional, two-dimensional, and higher-dimensional arrays.

One-Dimensional Array

1D Array
import numpy as np

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

print(numbers)

Two-Dimensional Array

2D Array
import numpy as np

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

print(matrix)
[[10 20 30] [40 50 60]]

Checking Dimensions

ndim
print(matrix.ndim)
2
7. Shape and Size

NumPy provides useful properties to understand the structure of an array.

shape and size
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: (2, 3) Size: 6 Dimensions: 2

shape tells you the size of each dimension, while size gives the total number of elements.

8. Indexing NumPy Arrays

NumPy uses zero-based indexing, just like Python lists.

Array Indexing
import numpy as np

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

print(numbers[0])
print(numbers[2])
print(numbers[-1])
10 30 50

Real-Time Example: Employee Salaries

Employee Salary
import numpy as np

salaries = np.array([35000, 42000, 50000, 60000, 75000])

print("First employee salary:", salaries[0])
print("Highest listed salary:", salaries[-1])
First employee salary: 35000 Highest listed salary: 75000
9. Slicing NumPy Arrays

Slicing allows you to extract a portion of an array.

Array Slicing
import numpy as np

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

print(numbers[1:4])
print(numbers[:3])
print(numbers[2:])
[20 30 40] [10 20 30] [30 40 50]

Real-Time Example: Sales Records

Recent Sales
import numpy as np

sales = np.array([12000, 15000, 18000, 21000, 25000])

recent_sales = sales[-3:]

print("Recent sales:", recent_sales)
Recent sales: [18000 21000 25000]
10. NumPy Arithmetic Operations

NumPy allows you to perform arithmetic operations directly on arrays.

Python Data
→
NumPy Array
→
Calculation
→
Result
Arithmetic Operations
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)
Add: [150 250 350] Subtract: [ 80 180 280] Multiply: [200 400 600] Divide: [ 50. 100. 150.]
11. Real-Time Example: Apply Discount to Products

Suppose an online store wants to apply a 10% discount to multiple products. NumPy can perform the calculation on the entire array.

E-Commerce Discount
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)
Original prices: [1000 1500 2000 2500] Discount: [100. 150. 200. 250.] Final prices: [ 900. 1350. 1800. 2250.]
12. NumPy Mathematical Functions

NumPy provides many mathematical functions that can operate directly on arrays.

Math Functions
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))
Square roots: [1. 2. 3. 4. 5.] Squares: [ 1 16 81 256 625] Maximum: 25 Minimum: 1
13. Sum, Mean, Minimum and Maximum

NumPy provides aggregation functions that are extremely useful when analyzing data.

Statistics
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))
Total: 1500 Average: 300.0 Minimum: 100 Maximum: 500

Real-Time Example: Monthly Sales

Monthly Sales Analysis
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))
14. Standard Deviation

Standard deviation measures how spread out values are from the average.

Standard Deviation
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.

15. Creating Arrays with zeros() and ones()

NumPy provides convenient functions for creating arrays filled with zeros or ones.

zeros and ones
import numpy as np

zeros = np.zeros(5)
ones = np.ones(5)

print("Zeros:", zeros)
print("Ones:", ones)
Zeros: [0. 0. 0. 0. 0.] Ones: [1. 1. 1. 1. 1.]

Creating a Matrix

Matrix
matrix = np.zeros((3, 4))

print(matrix)
[[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]
16. arange() Function

np.arange() creates evenly spaced values within a specified range.

arange
import numpy as np

numbers = np.arange(1, 11)

print(numbers)
[ 1 2 3 4 5 6 7 8 9 10]

Using a Step

Step Size
numbers = np.arange(0, 21, 5)

print(numbers)
[ 0 5 10 15 20]
17. linspace() Function

np.linspace() generates a specified number of evenly spaced values between two endpoints.

linspace
import numpy as np

values = np.linspace(0, 100, 6)

print(values)
[ 0. 20. 40. 60. 80. 100.]

This is useful when generating measurement intervals, plotting data, simulations, and scientific calculations.

18. Reshaping Arrays

The reshape() method changes the structure of an array without changing its data.

reshape
import numpy as np

numbers = np.arange(1, 13)

matrix = numbers.reshape(3, 4)

print(matrix)
[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
Important: The total number of elements must remain the same. For example, 12 elements can become a 3 × 4 matrix.
19. Flattening an Array

You can convert a multidimensional array into a one-dimensional array using flatten().

flatten
import numpy as np

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

flat = matrix.flatten()

print(flat)
[10 20 30 40 50 60]
20. Working with 2D Arrays

Two-dimensional arrays are useful for representing tables, matrices, images, spreadsheets, and other structured data.

2D Indexing
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])
First student: [80 75 90] First student's first mark: 80 Second student's third mark: 70

Real-Time Example: Student Marks

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)
Student averages: [81.66666667 73.33333333 91.]
21. Axis in NumPy

The axis argument tells NumPy which direction an operation should work along.

Axis Example
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))
Column averages: [76.66666667 80. 87.66666667] Row averages: [80. 73.33333333 91. ]
Remember: For a 2D array, axis=0 works down the rows, while axis=1 works across the columns of each row.
22. Boolean Filtering

NumPy can filter array elements using conditions.

Filtering Values
import numpy as np

prices = np.array([500, 1200, 800, 2000, 1500])

expensive = prices > 1000

print(expensive)
print(prices[expensive])
[False True False True True] [1200 2000 1500]

Real-Time Example: High-Value Orders

Order Filtering
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)
High-value orders: [1250 2300 1800]
23. Random Numbers with NumPy

NumPy provides random-number generation tools that are useful for simulations, testing, sampling, and modeling.

Random Integers
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

Customer Simulation
import numpy as np

customers = np.random.randint(50, 201, 7)

print("Customers for 7 days:", customers)
print("Average customers:", np.mean(customers))
24. Sorting NumPy Arrays

Use np.sort() to sort array values.

Sorting
import numpy as np

scores = np.array([75, 92, 68, 88, 95, 70])

sorted_scores = np.sort(scores)

print("Sorted scores:", sorted_scores)
Sorted scores: [68 70 75 88 92 95]

Descending Order

Descending Sort
descending = np.sort(scores)[::-1]

print(descending)
[95 92 88 75 70 68]
25. Concatenating Arrays

NumPy can combine multiple arrays using np.concatenate().

Concatenate Arrays
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)
[100 200 300 400 500 600]
26. Real-Time Example: Employee Salary Analysis

Imagine a company wants to analyze employee salaries. NumPy can calculate the total, average, minimum, maximum, and salaries above a particular threshold.

Employee Salary Analysis
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)
Total salary: 312000 Average salary: 52000.0 Minimum salary: 30000 Maximum salary: 72000 Salaries above 50000: [55000 72000 65000]
27. Real-Time Example: Temperature Analysis

NumPy can be used to analyze temperature measurements collected during a week.

Temperature Data
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)
Average temperature: 32.87142857142857 Highest temperature: 35.2 Lowest temperature: 30.8 Hot days: [33.1 34.5 35.2]
28. Real-Time Example: Student Performance Analysis

A school can use NumPy to calculate student averages and identify students who scored above a threshold.

Student Performance
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)
Average: 82.4 Highest: 95 Lowest: 67 Number passed: 10 High performers: [85 92 88 95 81 90]
29. Real-Time Example: Inventory Management

An inventory system can use NumPy arrays to identify products that need restocking.

Inventory Analysis
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))
Current stock: [50 8 25 3 45 6 70] Low-stock products: [8 3 6] Number of products needing restock: 3
30. Complete Real-Time Example: Sales Dashboard Data

The following example shows how NumPy can process sales data for a simple business dashboard.

Sales 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)
Total yearly sales: 263000 Average monthly sales: 21916.666666666668 Highest monthly sales: 32000 Lowest monthly sales: 12000 Months above average: [22000 25000 28000 30000 27000 32000]
31. NumPy Matrix Operations

NumPy can perform matrix calculations, which are important in engineering, data science, machine learning, and scientific computing.

Matrix Addition
import numpy as np

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

b = np.array([
    [5, 6],
    [7, 8]
])

result = a + b

print(result)
[[ 6 8] [10 12]]

Matrix Multiplication

Matrix Multiplication
result = a @ b

print(result)
[[19 22] [43 50]]
32. Copying NumPy Arrays

Use copy() when you need an independent copy of an array.

Array Copy
import numpy as np

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

copied = original.copy()

copied[0] = 100

print("Original:", original)
print("Copied:", copied)
Original: [10 20 30] Copied: [100 20 30]
The original array remains unchanged because copy() creates a separate array.
33. Useful NumPy Functions
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
34. NumPy vs Python List: When to Use NumPy

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
Remember: NumPy is not a replacement for every Python collection. For general-purpose heterogeneous data, dictionaries, sets, or objects, normal Python data structures may be more appropriate.
35. Important NumPy Rules
  • 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 shape to understand array dimensions.
  • Use ndim to find the number of dimensions.
  • Use size to find the total number of elements.
  • Use vectorized operations instead of unnecessary Python loops.
  • Use axis when 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.
36. Complete NumPy Example

Here is a complete example combining array creation, calculations, filtering, and statistics.

Complete Example
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)
Total revenue: 783000 Average revenue: 65250.0 Highest revenue: 90000 Lowest revenue: 45000 Above-average revenue: [68000 72000 65000 75000 81000 79000 90000]
This type of processing is commonly used as a building block for larger data-analysis and business-reporting applications.
Python NumPy — Arrays, numerical computing, mathematical operations, statistics, and real-time data processing.