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()andnp.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.
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
| 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]]
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.
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.
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:
- Create a one-dimensional zero array containing six elements.
- Create a two-dimensional zero array with three rows and four columns.
- Create a one-dimensional array of five ones using an integer data type.
- Generate a three-by-three identity matrix using
np.eye(). - Generate a four-by-four identity matrix using
np.identity(). - Create an identity-style array with three rows and four columns using
np.eye(). - 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
- What is the purpose of
np.zeros()? - How do you create a two-dimensional array of ones?
- What is an identity matrix?
- What is the difference between
np.eye()andnp.identity()? - How can you create an integer zero array?
- What does the
kparameter control innp.eye()? - Why should you select an appropriate data type?
- 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().