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 Array Fundamentals

Understand the structure of NumPy arrays, explore their dimensions, access array elements, and learn why arrays are important for numerical computing.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Define a NumPy array and explain its purpose.
  • Create arrays using np.array().
  • Identify zero-dimensional, one-dimensional, and multidimensional arrays.
  • Understand the difference between an array's shape, size, and dimensions.
  • Access individual array elements using indexes.
  • Compare basic Python lists with NumPy arrays.
  • Write simple programs that perform operations on arrays.

2. What Is a NumPy Array?

A NumPy array is a data structure provided by the NumPy library. It stores elements in an organized arrangement and supports efficient numerical operations.

NumPy arrays are commonly used for calculations involving measurements, marks, financial figures, scientific data, images, and mathematical models.

Example: Creating an Array

import numpy as np

marks = np.array([78, 85, 92, 67, 88])

print(marks)

Output:

[78 85 92 67 88]

Here, marks is a NumPy array containing five numerical elements. The function np.array() creates the array from the supplied sequence.

Remember: The standard NumPy import alias is np. Using this alias makes NumPy function calls shorter and easier to read.

3. Understanding Array Dimensions

An array's dimensions describe how its elements are arranged. A NumPy array can contain a single scalar value, a sequence of values, or data arranged across multiple dimensions.

0D Array 1D Array 2D Array 10 1 2 3 4 1 2 3 4 5 6 One scalar value One sequence Rows and columns ndim = 0 ndim = 1 ndim = 2
Figure 1: Examples of arrays with different numbers of dimensions.

Zero-Dimensional Array

import numpy as np

value = np.array(10)

print(value)
print(value.ndim)

Output:

10
0

A zero-dimensional array contains a single scalar value. It has no array axes.

One-Dimensional Array

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

print(numbers.ndim)

Output:

1

A one-dimensional array contains elements arranged along one axis.

Two-Dimensional Array

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print(matrix.ndim)
print(matrix.shape)

Output:

2
(2, 3)

This array has two rows and three columns. Its shape is (2, 3).

4. Creating Arrays from Python Lists

A Python list is a common way to provide data to np.array(). NumPy converts the supplied sequence into an array with an appropriate data type.

Integer Array

import numpy as np

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

print(numbers)

Floating-Point Array

prices = np.array([12.5, 20.0, 35.75])

print(prices)

Array from a Nested List

marks = np.array([
    [78, 85, 92],
    [67, 88, 81]
])

print(marks)

Output:

[[78 85 92]
 [67 88 81]]
Important: A regular multidimensional array generally requires compatible row lengths. When creating arrays from nested sequences, ensure the data has the intended structure.

5. Array Indexing Fundamentals

Indexing allows you to access an individual element in an array. NumPy uses zero-based indexing, which means the first element has index 0.

Example: Accessing Elements

import numpy as np

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

print(numbers[0])
print(numbers[2])
print(numbers[4])

Output:

10
30
50
10 20 30 40 50 Index 0 Index 1 Index 2 Index 3 Index 4 numbers[2] returns 30
Figure 2: Each element can be accessed using its index.

Using Negative Indexes

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

print(numbers[-1])
print(numbers[-2])

Output:

50
40

Negative indexes count from the end of the array. The index -1 refers to the last element.

Common error: Accessing an index outside the valid range raises an IndexError. For an array containing five elements, valid positive indexes are 0 through 4.

6. Understanding Shape, Size, and Dimensions

These properties describe different aspects of an array. Understanding the difference helps you verify that your data has the expected structure.

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
Property Result Explanation
shape (2, 3) Two rows and three columns.
size 6 Six elements in total.
ndim 2 Two dimensions.
Quick rule: Shape describes the size of each axis, size counts all elements, and ndim counts the number of axes.

7. Python Lists vs NumPy Arrays

Python lists and NumPy arrays can both store sequences of values, but their behavior and intended use differ.

Feature Python List NumPy Array
Creation [10, 20, 30] np.array([10, 20, 30])
Adding a scalar Not directly supported as element-wise addition. Adds the scalar to each element.
Multiplying by an integer Repeats the list. Multiplies each numerical element.
Numerical functions Usually requires built-in functions or explicit logic. Provides functions such as np.sum() and np.mean().
Multidimensional data Can use nested lists. Supports multidimensional arrays with shape and axis operations.

Compare the Results

import numpy as np

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

print(python_list * 2)
print(numpy_array * 2)

Output:

[10, 20, 30, 10, 20, 30]
[20 40 60]

Multiplication repeats a Python list, whereas multiplication of a numerical NumPy array applies the operation to each element.

8. Practical Program: Marks and Performance

Pradnya wants to inspect a set of marks and identify which values are greater than or equal to 80.

Complete Program

import numpy as np

marks = np.array([76, 89, 94, 68, 83])

print("All Marks:", marks)
print("First Mark:", marks[0])
print("Last Mark:", marks[-1])
print("Shape:", marks.shape)
print("Number of Elements:", marks.size)

high_marks = marks[marks >= 80]

print("Marks of 80 or Above:", high_marks)

Output:

All Marks: [76 89 94 68 83]
First Mark: 76
Last Mark: 83
Shape: (5,)
Number of Elements: 5
Marks of 80 or Above: [89 94 83]

The expression marks >= 80 produces a Boolean array. Using that condition inside square brackets selects the elements that satisfy it.

This technique is called Boolean indexing. It will be covered in greater detail in the Array Indexing and Slicing module.

9. Common Mistakes and Best Practices

1. Forgetting Zero-Based Indexing

The first element is at index 0, not index 1.

2. Confusing Shape and Size

A two-dimensional array with shape (2, 3) has six elements, not two or three.

3. Using List Arithmetic Expectations

List multiplication and NumPy array multiplication behave differently. Choose the structure that fits your calculation.

4. Ignoring Array Dimensions

A one-dimensional array and a two-dimensional array can contain similar values but have different shapes.

5. Accessing Invalid Indexes

Check the array length and use valid indexes to avoid an IndexError.

10. Classroom Practice Activity

Activity: Build and Inspect Arrays

At CIIT TRANING INSTITUTE, Samadhan, Pradnya, and Samiksha can complete this activity to practice NumPy array fundamentals.

  1. Create a one-dimensional array containing 5, 10, 15, 20, and 25.
  2. Print the first and last elements.
  3. Print the array's shape, size, and number of dimensions.
  4. Create a two-dimensional array with two rows and three columns.
  5. Print the shape and number of dimensions of the new array.
  6. Multiply the one-dimensional array by three and display the result.
  7. Select all values greater than 12 from the original array.

Starter Code

import numpy as np

numbers = np.array([5, 10, 15, 20, 25])

print("Array:", numbers)
print("First Element:", numbers[0])
print("Last Element:", numbers[-1])
print("Shape:", numbers.shape)
print("Size:", numbers.size)
print("Dimensions:", numbers.ndim)

print("Multiplied by 3:", numbers * 3)
print("Values Greater Than 12:", numbers[numbers > 12])

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print("Matrix Shape:", matrix.shape)
print("Matrix Dimensions:", matrix.ndim)

Review Questions

  1. What is a NumPy array?
  2. How do you create a NumPy array from a Python list?
  3. What is the difference between a one-dimensional and a two-dimensional array?
  4. What does the ndim attribute return?
  5. What is the difference between shape and size?
  6. What does the index -1 represent?
  7. How does multiplying a NumPy array differ from multiplying a Python list?
  8. How can you select array values that satisfy a condition?

Summary

In this lesson, you learned what NumPy arrays are and how to create them using np.array(). You explored zero-dimensional, one-dimensional, and two-dimensional arrays.

You practiced zero-based indexing, negative indexing, and the shape, size, and ndim attributes. You also compared Python lists with NumPy arrays and used Boolean conditions to select numerical values.