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

Arithmetic Array Operations

Learn how to perform element-wise addition, subtraction, multiplication, division, exponentiation, and remainder operations on NumPy arrays. Understand scalar arithmetic, mathematical operators, array calculations, and common numerical errors through detailed explanations and practical examples.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Understand element-wise arithmetic operations in NumPy.
  • Perform addition and subtraction on arrays.
  • Multiply and divide array elements.
  • Use exponentiation and remainder operators.
  • Perform arithmetic between arrays and scalar values.
  • Use NumPy arithmetic functions such as np.add() and np.multiply().
  • Understand the difference between element-wise multiplication and matrix multiplication.
  • Identify common arithmetic errors and handle numerical results carefully.

2. Introduction to Arithmetic Array Operations

NumPy provides arithmetic operations that work directly on arrays. These operations generally calculate results element by element, allowing you to process entire datasets without writing explicit Python loops.

For example, if two arrays contain corresponding student marks, NumPy can add or subtract the values at matching positions. The result is another array containing the calculated values.

import numpy as np first = np.array([10, 20, 30, 40]) second = np.array([1, 2, 3, 4]) result = first + second print(result)

Output:

[11 22 33 44]

NumPy adds the first elements, then the second elements, and continues until all corresponding elements have been processed. This is called an element-wise operation.

Element-wise Addition Array A Array B Result 10 20 30 40 1 2 3 4 11 22 33 44 + = Result

Each element is added to the element at the corresponding position.

3. Addition of NumPy Arrays

The addition operator + adds corresponding elements from two arrays. It is useful for combining values such as daily sales, student scores, expenses, or measurements.

import numpy as np morning_sales = np.array([100, 150, 200, 250]) evening_sales = np.array([120, 130, 180, 220]) total_sales = morning_sales + evening_sales print("Morning sales:", morning_sales) print("Evening sales:", evening_sales) print("Total sales:", total_sales)

Output:

Morning sales: [100 150 200 250] Evening sales: [120 130 180 220] Total sales: [220 280 380 470]

Each total represents the sum of morning and evening sales for the corresponding position. NumPy performs these calculations across the arrays in one expression.

Using np.add()

NumPy also provides the np.add() function. It performs the same element-wise addition as the + operator for compatible arrays.

import numpy as np a = np.array([5, 10, 15]) b = np.array([2, 4, 6]) print(a + b) print(np.add(a, b))

Output:

[ 7 14 21] [ 7 14 21]
Tip: Use + for concise arithmetic expressions. Use np.add() when its explicit function form improves clarity or when working with NumPy's function-based calculation patterns.

4. Subtraction of NumPy Arrays

The subtraction operator - subtracts each element in the second array from the corresponding element in the first array. The order matters because subtraction is not commutative.

import numpy as np original_marks = np.array([85, 90, 78, 92]) previous_marks = np.array([80, 85, 75, 88]) difference = original_marks - previous_marks print("Original marks:", original_marks) print("Previous marks:", previous_marks) print("Difference:", difference)

Output:

Original marks: [85 90 78 92] Previous marks: [80 85 75 88] Difference: [5 5 3 4]

The result indicates the difference between the two sets of marks at each position. A negative result would mean that the first value is smaller than the corresponding second value.

import numpy as np a = np.array([10, 20, 30]) b = np.array([15, 10, 35]) print(a - b) print(b - a)

Output:

[ -5 10 -5] [ 5 -10 5]
Remember: a - b and b - a usually produce different results because the order of operands changes the calculation.

5. Multiplication of NumPy Arrays

The multiplication operator * performs element-wise multiplication. Each value in the first array is multiplied by the value at the corresponding position in the second array.

import numpy as np quantity = np.array([2, 3, 4, 5]) price = np.array([100, 150, 200, 50]) amount = quantity * price print("Quantity:", quantity) print("Price:", price) print("Amount:", amount)

Output:

Quantity: [2 3 4 5] Price: [100 150 200 50] Amount: [200 450 800 250]

This example calculates the amount for each product by multiplying its quantity by its unit price. Each position in the result corresponds to one product.

Using np.multiply()

import numpy as np a = np.array([2, 4, 6]) b = np.array([3, 5, 7]) result = np.multiply(a, b) print(result)

Output:

[ 6 20 42]
Important: Element-wise multiplication is not the same as matrix multiplication. The * operator multiplies corresponding elements. Matrix multiplication uses operations such as @ or np.matmul().

6. Division of NumPy Arrays

The division operator / divides each element of the first array by the corresponding element of the second array. For ordinary integer and floating-point numeric arrays, true division generally produces floating-point results.

import numpy as np total_marks = np.array([80, 90, 75, 95]) number_of_subjects = np.array([2, 3, 3, 5]) result = total_marks / number_of_subjects print(result)

Output:

[40. 30. 25. 19.]

The operation calculates a quotient at each corresponding position. Floating-point results allow NumPy to represent fractional values when a division is not exact.

Using np.divide()

import numpy as np a = np.array([10, 20, 30]) b = np.array([2, 4, 5]) print(np.divide(a, b))

Output:

[ 5. 5. 6.]
Division by zero: Dividing floating-point values by zero can produce inf or nan and may raise a runtime warning. Check the denominator when zero values are not valid for your calculation.

Checking Denominators

import numpy as np numerator = np.array([10.0, 20.0, 30.0]) denominator = np.array([2.0, 0.0, 5.0]) result = np.zeros_like(numerator) np.divide( numerator, denominator, out=result, where=denominator != 0 ) print(result)

Output:

[ 5. 0. 6.]

In this example, division is performed only where the denominator is nonzero. The output array was initialized with zeros, so positions where the condition is false retain zero. Select a suitable fallback value for your application's requirements.

7. Exponentiation with NumPy Arrays

Exponentiation raises each element to a specified power. The ** operator performs element-wise exponentiation when used with compatible arrays.

import numpy as np values = np.array([2, 3, 4, 5]) squares = values ** 2 print("Values:", values) print("Squares:", squares)

Output:

Values: [2 3 4 5] Squares: [ 4 9 16 25]

Each element is multiplied by itself because the exponent is two. You can use other exponents depending on the mathematical calculation you need.

import numpy as np values = np.array([2, 3, 4]) print(values ** 3) print(np.power(values, 3))

Output:

[ 8 27 64] [ 8 27 64]

The np.power() function provides an explicit function-based way to perform element-wise exponentiation.

8. Remainder and Modulo Operations

The remainder operation returns the remainder after division. NumPy provides the % operator and the np.remainder() function for element-wise calculations.

import numpy as np values = np.array([10, 15, 20, 25]) divisors = np.array([3, 4, 6, 7]) result = values % divisors print(result)

Output:

[1 3 2 4]

For example, ten divided by three leaves a remainder of one. Fifteen divided by four leaves a remainder of three.

Checking Even and Odd Numbers

import numpy as np values = np.array([10, 11, 12, 13, 14, 15]) remainders = values % 2 print(remainders) print("Even numbers:", values[remainders == 0]) print("Odd numbers:", values[remainders != 0])

Output:

[0 1 0 1 0 1] Even numbers: [10 12 14] Odd numbers: [11 13 15]
Tip: Remainder operations are useful for identifying even and odd numbers, creating repeating patterns, and checking divisibility.

9. Arithmetic Between Arrays and Scalars

NumPy allows you to perform arithmetic between an array and a single scalar value. The scalar operation is applied to every element in the array.

import numpy as np marks = np.array([60, 70, 80, 90]) increased_marks = marks + 5 reduced_marks = marks - 10 doubled_marks = marks * 2 half_marks = marks / 2 print("Original:", marks) print("Increased:", increased_marks) print("Reduced:", reduced_marks) print("Doubled:", doubled_marks) print("Half:", half_marks)

Output:

Original: [60 70 80 90] Increased: [65 75 85 95] Reduced: [50 60 70 80] Doubled: [120 140 160 180] Half: [30. 35. 40. 45.]

Scalar arithmetic is useful when applying a constant adjustment to an entire dataset. For example, you can add a fixed bonus to marks or apply a common scaling factor to measurements.

Remember: The original array remains unchanged in these examples because each expression creates a new result array and assigns it to a separate variable.

10. Arithmetic Operations on Different Data Types

NumPy arrays have data types that influence how arithmetic operations are calculated and how results are stored. When different numeric types are combined, NumPy may promote the result to a compatible type.

import numpy as np integers = np.array([10, 20, 30], dtype=np.int32) decimals = np.array([1.5, 2.5, 3.5], dtype=np.float64) result = integers + decimals print(result) print(result.dtype)

Output:

[11.5 22.5 33.5] float64

The result uses a floating-point type so that fractional parts can be represented. The precise result type depends on the input dtypes and NumPy's type-promotion rules.

Watch integer overflow: Fixed-width integer types have limited numeric ranges. Large arithmetic results may overflow the chosen type. Select an appropriate data type and inspect the resulting dtype when working with large values.

11. Understanding Element-Wise Multiplication and Matrix Multiplication

Element-wise multiplication and matrix multiplication are different operations. Element-wise multiplication multiplies matching elements. Matrix multiplication combines rows and columns according to linear algebra rules.

import numpy as np a = np.array([ [1, 2], [3, 4] ]) b = np.array([ [5, 6], [7, 8] ]) elementwise = a * b matrix_product = a @ b print("Element-wise multiplication:") print(elementwise) print("Matrix multiplication:") print(matrix_product)

Output:

Element-wise multiplication: [[ 5 12] [21 32]] Matrix multiplication: [[19 22] [43 50]]
Operation Operator Meaning
Element-wise multiplication * Multiplies values at corresponding positions.
Matrix multiplication @ Combines rows of the first matrix with columns of the second matrix.
Matrix multiplication function np.matmul() Performs matrix multiplication using NumPy's function API.
Best practice: Before using @, verify that the number of columns in the first matrix equals the number of rows in the second matrix.

12. Common Arithmetic Errors

Incompatible Array Shapes

Arithmetic between two arrays requires compatible shapes. NumPy supports broadcasting, which allows certain differently shaped arrays to work together. However, incompatible shapes produce an error.

import numpy as np a = np.array([10, 20, 30]) b = np.array([1, 2]) # These arrays have incompatible shapes for element-wise addition. # result = a + b print("Shape of a:", a.shape) print("Shape of b:", b.shape)

Output:

Shape of a: (3,) Shape of b: (2,)

The arrays have lengths three and two. Their shapes cannot be aligned under NumPy's broadcasting rules, so adding them directly would raise a ValueError.

Integer Division

When integer quotients are required, use // for floor division. Unlike true division, floor division returns the floor of the quotient.

import numpy as np a = np.array([10, 17, 20]) b = np.array([3, 5, 6]) print(a / b) print(a // b)

Output:

[3.33333333 3.4 3.33333333] [3 3 3]
Important: Floor division rounds down toward negative infinity. For negative values, it is not the same as simply removing the decimal part.

13. Practical Activity

Activity: Sales and Revenue Calculations

Samadhan, Pradnya, and Samiksha are analyzing daily sales for four products. The dataset contains quantities sold, unit prices, and discounts. Use NumPy arithmetic operations to calculate revenue and adjusted values.

Tasks:

  1. Create arrays for product quantities and unit prices.
  2. Calculate total revenue for each product.
  3. Apply a fixed discount to each revenue value.
  4. Calculate the difference between original and adjusted revenue.
  5. Use the remainder operator to identify quantities that are even.
  6. Display the resulting arrays and their data types.

Sample Solution

import numpy as np quantities = np.array([2, 3, 4, 5]) prices = np.array([100, 150, 200, 50]) revenue = quantities * prices discount = 10 adjusted_revenue = revenue - discount difference = revenue - adjusted_revenue even_quantities = quantities[quantities % 2 == 0] print("Quantities:", quantities) print("Prices:", prices) print("Revenue:", revenue) print("Adjusted revenue:", adjusted_revenue) print("Difference:", difference) print("Even quantities:", even_quantities) print("Revenue dtype:", revenue.dtype)

Expected key results:

  • Revenue: [200, 450, 800, 250]
  • Adjusted revenue: [190, 440, 790, 240]
  • Difference: [10, 10, 10, 10]
  • Even quantities: [2, 4]

Summary

In this lesson, we learned how to perform arithmetic operations on NumPy arrays using addition, subtraction, multiplication, division, exponentiation, and remainder operators. We explored the equivalent NumPy functions, including add(), subtract(), multiply(), divide(), and power(), and learned how scalar arithmetic applies a calculation to every element in an array.

We also compared element-wise multiplication with matrix multiplication, examined data type promotion, and discussed common issues such as incompatible array shapes, division by zero, and integer overflow. These operations make numerical calculations concise and efficient. Always check array shapes, data types, and denominator values when necessary to ensure that arithmetic results are appropriate for your application.