Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

NumPy Mathematical Functions

NumPy provides a rich collection of mathematical functions for performing calculations on individual values and entire arrays. These functions make numerical programs faster, cleaner, and easier to maintain. In this lesson, you will learn how to perform arithmetic calculations, calculate powers and square roots, work with absolute values, and apply common mathematical functions to arrays.

1. Introduction to Mathematical Functions

Mathematical functions perform operations such as addition, subtraction, multiplication, division, exponentiation, and square-root calculation. NumPy functions can operate directly on arrays without requiring you to write a separate loop for every element.

Why Use NumPy Mathematical Functions?

  • Perform calculations on complete arrays.
  • Reduce the need for manual loops.
  • Write concise and readable numerical code.
  • Use consistent operations on NumPy arrays.
  • Combine mathematical functions in data analysis workflows.
import numpy as np marks = np.array([65, 72, 84, 91, 78]) bonus_marks = marks + 5 print("Original marks:", marks) print("Updated marks:", bonus_marks)

Output:

Original marks: [65 72 84 91 78] Updated marks: [70 77 89 96 83]

Here, NumPy adds five to every element in the array. The original array remains unchanged because the result is assigned to a new variable.

2. Basic Arithmetic Operations

NumPy supports the standard arithmetic operators. When these operators are applied to compatible arrays, the operation is performed element by element.

Operation Operator NumPy Example Result
Addition + a + b [11, 22, 33]
Subtraction - a - b [-9, -18, -27]
Multiplication * a * b [10, 40, 90]
Division / a / b [0.1, 0.1, 0.1]
Exponentiation ** a ** 2 Squares each element
Remainder % a % b Element-wise remainders
import numpy as np a = np.array([1, 2, 3]) b = np.array([10, 20, 30]) print("Addition:", a + b) print("Subtraction:", a - b) print("Multiplication:", a * b) print("Division:", a / b) print("Square:", a ** 2) print("Remainder:", b % 4)

Output:

Addition: [11 22 33] Subtraction: [ -9 -18 -27] Multiplication: [10 40 90] Division: [0.1 0.1 0.1] Square: [1 4 9] Remainder: [2 0 2]
Tip: Arithmetic operators are convenient for everyday array calculations. NumPy also provides named functions such as np.add(), np.subtract(), and np.multiply().

3. Using NumPy Arithmetic Functions

Named arithmetic functions provide an alternative to operators. They are useful when you want to make the purpose of an operation explicit in your code.

import numpy as np prices = np.array([100, 250, 400]) discounts = np.array([10, 25, 40]) final_prices = np.subtract(prices, discounts) total_values = np.add(prices, discounts) scaled_prices = np.multiply(prices, 2) print("Final prices:", final_prices) print("Added values:", total_values) print("Double prices:", scaled_prices)

Output:

Final prices: [ 90 225 360] Added values: [110 275 440] Double prices: [200 500 800]

Common Arithmetic Functions

Function Purpose
np.add(a, b) Adds corresponding elements.
np.subtract(a, b) Subtracts corresponding elements.
np.multiply(a, b) Multiplies corresponding elements.
np.divide(a, b) Divides corresponding elements.
np.remainder(a, b) Calculates the remainder for corresponding elements.
np.power(a, b) Raises each element of a to the corresponding power in b.

4. Square Roots and Powers

NumPy provides functions for calculating square roots and powers. These operations are frequently used in geometry, scientific calculations, statistics, and data processing.

Square Root with np.sqrt()

import numpy as np values = np.array([4, 9, 16, 25, 36]) result = np.sqrt(values) print(result)

Output:

[2. 3. 4. 5. 6.]

Power with np.power()

import numpy as np bases = np.array([2, 3, 4, 5]) powers = np.array([2, 2, 3, 2]) result = np.power(bases, powers) print(result)

Output:

[ 4 9 64 25]

Each element in bases is raised to the power at the same position in powers.

Square Root sqrt([4, 9, 16, 25]) [2, 3, 4, 5] Power power([2, 3, 4], 2) [4, 9, 16]

NumPy applies square-root and power calculations element by element.

5. Absolute Values and Sign Functions

The absolute value represents the distance of a number from zero, without considering its sign. The np.abs() function calculates absolute values, while np.sign() identifies whether each value is negative, zero, or positive.

import numpy as np values = np.array([-15, -4, 0, 7, 22]) print("Absolute values:", np.abs(values)) print("Signs:", np.sign(values))

Output:

Absolute values: [15 4 0 7 22] Signs: [-1 -1 0 1 1]
Function Meaning Example
np.abs() Returns absolute values. np.abs(-8) returns 8.
np.sign() Returns the sign of a value. Negative values return -1, zero returns 0, and positive values return 1.

6. Exponential and Logarithmic Functions

Exponential functions calculate powers of a base, while logarithmic functions help determine the exponent associated with a value. They are useful in scientific computing, growth calculations, and numerical models.

Exponential Calculation

import numpy as np values = np.array([0, 1, 2]) print(np.exp(values))

Output:

[1. 2.71828183 7.3890561 ]

The np.exp() function calculates \(e^x\) for each element, where \(e\) is approximately 2.71828.

Natural Logarithm

import numpy as np values = np.array([1, np.e, np.e ** 2]) print(np.log(values))

Output:

[0. 1. 2.]

Other Logarithmic Functions

Function Description
np.log() Natural logarithm (base e).
np.log10() Logarithm with base 10.
np.log2() Logarithm with base 2.
np.exp() Exponential function with base e.
np.exp2() Calculates powers of 2.
Important: Logarithms of zero and negative real numbers do not produce finite real-number results. Check your input values when working with logarithmic calculations.

7. Rounding Mathematical Values

Rounding functions change the precision or integer direction of numerical values. They are helpful when displaying results or preparing numerical data for further processing.

import numpy as np values = np.array([2.3, 2.7, 3.5, -2.3, -2.7]) print("Round:", np.round(values)) print("Floor:", np.floor(values)) print("Ceiling:", np.ceil(values)) print("Truncate:", np.trunc(values))

Output:

Round: [ 2. 3. 4. -2. -3.] Floor: [ 2. 2. 3. -3. -3.] Ceiling: [ 3. 3. 4. -2. -2.] Truncate: [ 2. 2. 3. -2. -2.]
Function Behavior
np.round() Rounds to the nearest value, using ties-to-even for exact halfway cases.
np.floor() Rounds down toward negative infinity.
np.ceil() Rounds up toward positive infinity.
np.trunc() Removes the fractional part by moving toward zero.
Remember: Floor and truncation are different for negative numbers. For example, the floor of -2.7 is -3, while its truncated value is -2.

8. Working with Remainders and Quotients

NumPy provides functions for calculating the remainder and quotient of division. These are useful when dividing values into groups, checking divisibility, and performing integer-based calculations.

import numpy as np numbers = np.array([10, 17, 24, 31]) divisors = np.array([3, 5, 6, 7]) print("Remainders:", np.remainder(numbers, divisors)) print("Floor division:", np.floor_divide(numbers, divisors))

Output:

Remainders: [1 2 0 3] Floor division: [3 3 4 4]

np.remainder() returns the remainder after division. np.floor_divide() returns the quotient rounded down toward negative infinity.

9. Applying Multiple Functions to an Array

Mathematical functions can be combined to create a calculation pipeline. Each step can use the result of the previous operation.

Example: Processing Student Marks

Samadhan, Pradnya, and Samiksha receive marks in a test. We will add bonus marks, calculate the square root of the updated values, and round the results for display.

import numpy as np students = np.array(["Samadhan", "Pradnya", "Samiksha"]) marks = np.array([64, 81, 90]) updated_marks = np.add(marks, 4) root_values = np.sqrt(updated_marks) rounded_roots = np.round(root_values, 2) for name, mark, root in zip(students, updated_marks, rounded_roots): print(name, "- Updated Marks:", mark, "- Square Root:", root)

Output:

Samadhan - Updated Marks: 68 - Square Root: 8.25 Pradnya - Updated Marks: 85 - Square Root: 9.22 Samiksha - Updated Marks: 94 - Square Root: 9.7

NumPy performs the numerical calculations on the arrays. The loop is used only to display each student's name alongside the calculated values.

10. Common Mistakes and Best Practices

Check Array Compatibility

Element-wise operations require compatible array shapes. NumPy broadcasting allows some differently shaped arrays to work together, but incompatible shapes raise an error.

Understand Division by Zero

Division by zero in floating-point arrays can produce infinity or NaN and may generate a warning. Integer division has different constraints and may raise an error.

Use Appropriate Input Values

Functions such as square root and logarithm have domain restrictions when working with real-valued data. Check whether your inputs are appropriate for the calculation.

Keep Precision in Mind

Floating-point results may contain small representation differences. Use np.round() for presentation when needed, but avoid rounding intermediate calculations unnecessarily.

import numpy as np values = np.array([1.23456, 2.34567, 3.45678]) calculated = np.sqrt(values) display_values = np.round(calculated, 2) print("Calculated:", calculated) print("Display values:", display_values)

Output:

Calculated: [1.11110756 1.53155854 1.85924115] Display values: [1.11 1.53 1.86]

11. Practice Exercises

Exercise 1: Basic Calculations

Create an array containing [12, 18, 24, 30]. Add 5 to every element, multiply the result by 2, and print the final array.

Exercise 2: Square Roots and Powers

Create an array containing [9, 16, 25, 49]. Calculate its square roots and squares using NumPy functions.

Exercise 3: Absolute Values

Use np.abs() on [-12, -5, 0, 7, 15]. Then use np.sign() to inspect the signs.

Exercise 4: Rounding

Apply np.round(), np.floor(), np.ceil(), and np.trunc() to [3.2, 3.8, -3.2, -3.8]. Compare the outputs.

Exercise 5: Combined Mathematical Operations

Create an array of prices [120, 250, 480]. Apply a 10 percent increase, calculate the square root of the updated prices, and round the results to two decimal places.

Summary

NumPy mathematical functions provide efficient ways to calculate values across arrays. They support basic arithmetic, powers, square roots, absolute values, exponential and logarithmic operations, rounding, quotients, and remainders.

  • Use arithmetic operators or functions such as np.add() and np.multiply().
  • Use np.sqrt() for square roots and np.power() for exponentiation.
  • Use np.abs() and np.sign() to examine numeric values.
  • Use np.exp() and logarithmic functions for exponential calculations.
  • Use np.round(), np.floor(), np.ceil(), and np.trunc() according to the required rounding behavior.
  • Check input values, array shapes, and numerical precision when performing calculations.

These functions form the foundation for more advanced NumPy topics, including statistical analysis, data filtering, and numerical computing.