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

Zeros, Ones and Identity Arrays

Learn to initialize arrays with zeros and ones, create identity matrices, specify array shapes, and use these functions in practical numerical programs.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Create arrays filled with zeros using np.zeros().
  • Create arrays filled with ones using np.ones().
  • Generate identity matrices using np.eye() and np.identity().
  • Specify one-dimensional and multidimensional array shapes.
  • Choose suitable data types for initialized arrays.
  • Use initialized arrays in mathematical and data-processing tasks.

2. What Are Initialized Arrays?

An initialized array is an array created with predefined starting values. Instead of entering each element manually, NumPy can fill an entire array with a selected value.

For example, an array filled with zeros may represent initial measurements, while an array filled with ones may be useful for creating starting values in calculations.

Common Array Initialization Functions

Function Purpose
np.zeros() Creates an array filled with zeros.
np.ones() Creates an array filled with ones.
np.eye() Creates a two-dimensional array with ones on a selected diagonal.
np.identity() Creates a square identity matrix.

3. Creating Arrays with np.zeros()

The np.zeros() function creates an array of the requested shape with every element initialized to zero.

General syntax:

np.zeros(shape, dtype=float)

The shape parameter specifies the array's dimensions. The optional dtype parameter determines the data type of its elements.

Example 1: One-Dimensional Zero Array

import numpy as np

values = np.zeros(5)

print(values)

Output:

[0. 0. 0. 0. 0.]

By default, np.zeros() creates floating-point values.

Example 2: Two-Dimensional Zero Array

matrix = np.zeros((2, 3))

print(matrix)

Output:

[[0. 0. 0.]
 [0. 0. 0.]]

The shape (2, 3) creates two rows and three columns.

Example 3: Integer Zero Array

values = np.zeros(4, dtype=int)

print(values)
print(values.dtype)

Output:

[0 0 0 0]
int64

The exact integer data type can vary by platform. Check values.dtype to inspect the actual type.

Tip: Use np.zeros() when you need an array with a known shape and every element should begin at zero.

4. Creating Arrays with np.ones()

The np.ones() function creates an array with the requested shape and fills every element with one.

General syntax:

np.ones(shape, dtype=float)

Example 1: One-Dimensional Ones Array

import numpy as np

values = np.ones(5)

print(values)

Output:

[1. 1. 1. 1. 1.]

Example 2: Two-Dimensional Ones Array

matrix = np.ones((3, 2))

print(matrix)

Output:

[[1. 1.]
 [1. 1.]
 [1. 1.]]

Example 3: Integer Ones Array

values = np.ones((2, 3), dtype=int)

print(values)

Output:

[[1 1 1]
 [1 1 1]]

The np.ones() function is useful when a calculation needs a starting array containing ones, such as a simple mask or a set of initial multipliers.

5. Visual Comparison: Zeros and Ones

Zeros Array Ones Array Identity Matrix 0 0 0 0 1 1 1 1 1 1 1 Every element is 0 Every element is 1 Diagonal elements are 1
Figure 1: Zero arrays, one arrays, and a square identity matrix.
Function Example Resulting values
np.zeros(3) Three elements [0., 0., 0.]
np.ones(3) Three elements [1., 1., 1.]
np.eye(3) Three-by-three matrix Ones on the main diagonal and zeros elsewhere.

6. Creating an Identity Matrix with np.eye()

An identity matrix is a square matrix with ones on its main diagonal and zeros everywhere else. It is commonly used in linear algebra.

General syntax:

np.eye(N, M=None, k=0, dtype=float)
Parameter Meaning
N Number of rows.
M Optional number of columns. Defaults to N.
k Diagonal offset. Zero selects the main diagonal.
dtype Data type of the array elements.

Example 1: Three-by-Three Identity Matrix

import numpy as np

identity_matrix = np.eye(3)

print(identity_matrix)

Output:

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

Example 2: Identity Matrix with Integer Values

identity_matrix = np.eye(4, dtype=int)

print(identity_matrix)

Output:

[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]

Example 3: Shift the Diagonal

matrix = np.eye(3, k=1, dtype=int)

print(matrix)

Output:

[[0 1 0]
 [0 0 1]
 [0 0 0]]
Remember: The default value of k=0 selects the main diagonal. A positive value moves the diagonal above it, while a negative value moves it below.

7. Creating an Identity Matrix with np.identity()

The np.identity() function creates a square identity matrix. Its argument specifies the number of rows and columns.

Example: Create a Four-by-Four Identity Matrix

import numpy as np

matrix = np.identity(4, dtype=int)

print(matrix)

Output:

[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]
Feature np.eye() np.identity()
Square matrix Supported. Supported.
Different row and column counts Supported using N and M. Not supported; creates a square matrix.
Diagonal offset Supported using k. No diagonal offset parameter.
Typical use Flexible diagonal matrix patterns. Standard square identity matrix.

8. Choosing a Data Type

Array creation functions accept a dtype argument. This allows you to choose how values are represented.

Example: Integer and Floating-Point Arrays

import numpy as np

integer_zeros = np.zeros(4, dtype=int)
decimal_ones = np.ones(4, dtype=float)
integer_identity = np.eye(3, dtype=int)

print(integer_zeros)
print(decimal_ones)
print(integer_identity)

Output:

[0 0 0 0]
[1. 1. 1. 1.]
[[1 0 0]
 [0 1 0]
 [0 0 1]]

Select a data type that matches the calculations you plan to perform. Integer arrays are useful for whole-number data, while floating-point arrays support fractional values.

Important: If you store decimal values in an integer array, the values may be converted to integers. Choose the data type deliberately when precision matters.

9. Practical Program: Initialize a Marks Table

Samadhan wants to prepare an initial table for three subjects across two practice records. He will initialize the table with zeros and then fill it with sample marks.

Complete Program

import numpy as np

marks = np.zeros((2, 3), dtype=int)

marks[0] = [78, 85, 90]
marks[1] = [82, 88, 91]

print("Marks Table:")
print(marks)

print("Total Marks:", np.sum(marks, axis=1))

Output:

Marks Table:
[[78 85 90]
 [82 88 91]]
Total Marks: [253 261]

The zero array provides a starting structure with two rows and three columns. The program then assigns values to each row and calculates each row's total.

Practical insight: Initializing an array with zeros can make it easier to prepare a fixed-size data structure before filling it with actual measurements.

10. Common Mistakes and Best Practices

1. Passing an Incorrect Shape

Use an integer such as 5 for a one-dimensional array, or a tuple such as (2, 3) for a two-dimensional array.

2. Confusing Zeros and Ones

np.zeros() fills the array with zeros, while np.ones() fills it with ones.

3. Assuming np.identity() Supports Rectangular Matrices

np.identity() creates square matrices. Use np.eye() when you need different row and column counts.

4. Forgetting the Default Data Type

Zero and one arrays use floating-point values by default. Specify dtype=int if integer values are required.

5. Using an Unnecessary Identity Matrix

An identity matrix is useful for specific mathematical operations. For ordinary initialized data, a zero or one array may be more appropriate.

11. Classroom Practice Activity

Activity: Create and Inspect Initialized Arrays

At CIIT TRANING INSTITUTE, Pradnya and Samiksha are practicing array initialization. Complete these tasks:

  1. Create a one-dimensional zero array containing six elements.
  2. Create a two-dimensional zero array with three rows and four columns.
  3. Create a one-dimensional array of five ones using an integer data type.
  4. Generate a three-by-three identity matrix using np.eye().
  5. Generate a four-by-four identity matrix using np.identity().
  6. Create an identity-style array with three rows and four columns using np.eye().
  7. Display the shape and data type of each array.

Starter Code

import numpy as np

zero_array = np.zeros(6)
zero_matrix = np.zeros((3, 4))
one_array = np.ones(5, dtype=int)

identity_eye = np.eye(3, dtype=int)
identity_square = np.identity(4, dtype=int)
rectangular_eye = np.eye(3, 4, dtype=int)

print("Zero Array:", zero_array)
print("Zero Matrix:")
print(zero_matrix)

print("One Array:", one_array)
print("Identity with eye():")
print(identity_eye)

print("Identity with identity():")
print(identity_square)

print("Rectangular eye Array:")
print(rectangular_eye)

print("Zero Matrix Shape:", zero_matrix.shape)
print("One Array Type:", one_array.dtype)

Review Questions

  1. What is the purpose of np.zeros()?
  2. How do you create a two-dimensional array of ones?
  3. What is an identity matrix?
  4. What is the difference between np.eye() and np.identity()?
  5. How can you create an integer zero array?
  6. What does the k parameter control in np.eye()?
  7. Why should you select an appropriate data type?
  8. How can an initialized array be useful in a practical data-processing task?

Summary

In this lesson, you learned to create zero-filled arrays with np.zeros() and one-filled arrays with np.ones(). You also practiced specifying array shapes and choosing suitable data types.

You explored identity matrices using np.eye() and np.identity(), including diagonal offsets and rectangular arrays created with np.eye().