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

Two-Dimensional Array Indexing

Learn how to access individual elements, rows, and columns in two-dimensional NumPy arrays. Understand row and column indexes, negative indexing, element modification, and practical matrix operations.

1. Learning Objectives

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

  • Understand the structure of a two-dimensional NumPy array.
  • Identify row indexes and column indexes.
  • Access individual elements using row and column positions.
  • Select complete rows and columns.
  • Use negative indexes to access elements from the end.
  • Modify individual elements and complete rows.
  • Combine indexing with slicing to select portions of a matrix.
  • Apply two-dimensional indexing to a practical dataset.
Beginner tip: In a two-dimensional NumPy array, the first index identifies the row and the second index identifies the column.

2. What Is a Two-Dimensional Array?

A two-dimensional array stores data in rows and columns. It is commonly used to represent tables, matrices, student marks, sales records, and other structured information.

Each element has two index positions: one for its row and one for its column. NumPy uses zero-based indexing, which means the first row and first column both have index 0.

Example: Student Marks Table

Samadhan stores the marks of three students across four subjects. Each row represents a student, while each column represents a subject.

import numpy as np marks = np.array([ [78, 85, 90, 88], [82, 79, 94, 91], [75, 88, 84, 86] ]) print(marks)
Row / Student Subject 0 Subject 1 Subject 2 Subject 3
Row 0 78 85 90 88
Row 1 82 79 94 91
Row 2 75 88 84 86
Figure 1: A two-dimensional array containing marks for three students.

3. Understanding Row and Column Indexes

NumPy indexes begin at zero. For a two-dimensional array, the first number represents the row index and the second number represents the column index.

The general syntax for accessing an element is:

array[row_index, column_index]
Row and Column Indexes Column 0 Column 1 Column 2 Column 3 Row 0 Row 1 Row 2 78 85 90 88 82 79 94 91 75 88 84 86 marks[1, 1] = 79 Row index 1 and column index 1 identify the highlighted element.
Figure 2: The first index identifies the row and the second identifies the column.
Remember: marks[1, 1] selects the element at row index 1 and column index 1. It returns the value 79 in this example.

4. Accessing Individual Elements

To retrieve a single value from a two-dimensional array, provide both its row index and its column index.

marks = np.array([ [78, 85, 90, 88], [82, 79, 94, 91], [75, 88, 84, 86] ]) print(marks[0, 0]) # Output: 78 print(marks[0, 2]) # Output: 90 print(marks[1, 3]) # Output: 91 print(marks[2, 1]) # Output: 88
Expression Meaning Output
marks[0, 0] First row, first column 78
marks[0, 2] First row, third column 90
marks[1, 3] Second row, fourth column 91
marks[2, 1] Third row, second column 88

5. Selecting Complete Rows

To select an entire row, specify the row index and use a colon for the column selection. The colon means that all columns should be selected.

marks = np.array([ [78, 85, 90, 88], [82, 79, 94, 91], [75, 88, 84, 86] ]) # Select the first row print(marks[0, :]) # Output: [78 85 90 88] # Select the second row print(marks[1, :]) # Output: [82 79 94 91] # Select the third row print(marks[2, :]) # Output: [75 88 84 86]

You can also use the shorter form marks[0] to select the first row.

print(marks[0]) # Output: [78 85 90 88]
Practical use: Row indexing is useful when you want to examine all the values associated with one student, one product, or one particular record.

6. Selecting Complete Columns

To select a complete column, use a colon for the row selection and specify the required column index.

marks = np.array([ [78, 85, 90, 88], [82, 79, 94, 91], [75, 88, 84, 86] ]) # Select the first column print(marks[:, 0]) # Output: [78 82 75] # Select the second column print(marks[:, 1]) # Output: [85 79 88] # Select the third column print(marks[:, 2]) # Output: [90 94 84] # Select the fourth column print(marks[:, 3]) # Output: [88 91 86]
Selecting a Complete Column Column 0 Column 1 Column 2 Column 3 90 94 84 marks[:, 2] → [90 94 84]
Figure 3: A colon selects all rows while column index 2 selects the third column.
Remember: In marks[:, 2], the first colon selects every row and the number 2 selects column index 2.

7. Using Negative Indexes

Negative indexes allow you to access rows and columns from the end of the array. The index -1 represents the last row or column, depending on which position it is used in.

marks = np.array([ [78, 85, 90, 88], [82, 79, 94, 91], [75, 88, 84, 86] ]) # Last row, last column print(marks[-1, -1]) # Output: 86 # Last row print(marks[-1, :]) # Output: [75 88 84 86] # Last column print(marks[:, -1]) # Output: [88 91 86] # First row, last column print(marks[0, -1]) # Output: 88
Expression Description
marks[-1, -1] Selects the last element of the last row.
marks[-1, :] Selects the complete last row.
marks[:, -1] Selects the complete last column.
marks[0, -1] Selects the last element in the first row.

8. Modifying Elements in a Two-Dimensional Array

You can update an element by assigning a new value to its row and column position.

marks = np.array([ [78, 85, 90, 88], [82, 79, 94, 91], [75, 88, 84, 86] ]) # Update the element at row 0, column 1 marks[0, 1] = 95 print(marks) # Output: # [[78 95 90 88] # [82 79 94 91] # [75 88 84 86]]

Updating a Complete Row

marks[1, :] = [80, 85, 90, 95] print(marks)

When replacing a complete row, the number of replacement values must match the row's length and the values must be compatible with the array's data type.

Important: NumPy arrays have a data type. Assigning a value of a different type may cause conversion, and some assignments may fail if the value cannot be converted.

9. Combining Indexing and Slicing

You can combine individual indexes and slices to select a specific part of a matrix. This is particularly useful when working with large tables.

data = np.array([ [10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120], [130, 140, 150, 160] ]) # Select the first two rows and middle two columns print(data[0:2, 1:3]) # Output: # [[20 30] # [60 70]] # Select the last two rows print(data[-2:, :]) # Select the first three rows and first two columns print(data[:3, :2])
Expression Selected Data
data[0:2, 1:3] First two rows and columns 1 and 2.
data[-2:, :] Last two rows and every column.
data[:3, :2] First three rows and first two columns.

10. Common Indexing Errors

Error Reason Solution
IndexError: index out of bounds The requested row or column index does not exist. Check the array shape and use valid indexes.
Incorrect row and column order The row and column positions have been reversed. Use array[row, column].
Forgetting the comma Two-dimensional indexing needs separate row and column selections. Write array[1, 2] instead of treating both indexes as one.
Confusing index and position NumPy starts indexing at zero. Remember that the first row and column have index 0.
Incorrect assignment length The replacement row does not match the required shape. Provide compatible values with the expected dimensions.
Debugging tip: Use array.shape to check the number of rows and columns before accessing elements.
print(marks.shape) # Example output: (3, 4) print(marks.ndim) # Output: 2

11. Practical Activity: Student Marks Analysis

Activity: Access and Update Student Marks

Samiksha is reviewing marks for three students across four subjects. Use two-dimensional indexing to retrieve selected marks, display a complete row and column, and update one value.

import numpy as np marks = np.array([ [78, 85, 90, 88], [82, 79, 94, 91], [75, 88, 84, 86] ]) # Access one mark print("Selected mark:", marks[1, 2]) # Display all marks in the first row print("First student:", marks[0, :]) # Display marks in the second subject print("Second subject:", marks[:, 1]) # Access the final mark in the array print("Final mark:", marks[-1, -1]) # Update one mark marks[0, 0] = 80 print("Updated marks:") print(marks)

Expected Output

Selected mark: 94 First student: [78 85 90 88] Second subject: [85 79 88] Final mark: 86 Updated marks: [[80 85 90 88] [82 79 94 91] [75 88 84 86]]

12. Practice Exercises

Use this array to complete the following exercises:

sales = np.array([ [120, 150, 180, 200], [100, 130, 170, 190], [140, 160, 210, 230] ])
  1. Access the value 180 using row and column indexes.
  2. Select the first row.
  3. Select the third row.
  4. Select the second column.
  5. Access the last value in the array using negative indexes.
  6. Select the first two rows and the first three columns.
  7. Change the value at row index 1 and column index 2 to 175.
  8. Print the shape of the array.

Challenge Exercise

Pradnya has a matrix containing monthly sales for four products. Create a two-dimensional NumPy array with at least four rows and three columns. Then:

  • Display the second product's complete row.
  • Display the first month's sales for every product.
  • Retrieve the last value of the last row.
  • Update one selected sales value.
  • Extract a rectangular section of the array using slicing.

Summary

In this lesson, we learned how two-dimensional NumPy arrays organize data into rows and columns. We used array[row, column] to access individual elements, selected complete rows and columns, and explored negative indexes.

We also learned how to update elements, combine indexing with slicing, inspect array dimensions, and recognize common indexing errors. These skills are essential when analyzing tables, matrices, and structured datasets.

Practice the examples using different arrays to build confidence with row and column indexing.

In the next lesson, you will learn how Boolean indexing and fancy indexing can select array elements using conditions and lists of indexes.