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 Where, Select and Nonzero Functions

NumPy provides several functions for conditional selection and locating elements in arrays. The np.where() function selects values or returns matching indices, np.select() applies multiple conditions, and np.nonzero() identifies positions of nonzero elements. In this lesson, you will learn how these functions work and how to apply them to practical datasets.

1. Introduction to np.where()

The np.where() function supports conditional selection. When supplied with a condition, it returns the indices where the condition is True. When supplied with a condition and two choices, it selects a value from one of the choices for each element.

import numpy as np values = np.array([10, 25, 40, 15, 60]) indices = np.where(values > 30) print("Matching indices:", indices[0]) print("Matching values:", values[indices])

Output:

Matching indices: [2 4] Matching values: [40 60]

The condition values > 30 is evaluated element by element. The matching elements occur at indices 2 and 4.

Two Common Forms

  • np.where(condition) returns indices where the condition is True.
  • np.where(condition, x, y) chooses elements from x or y.

2. Selecting Values with np.where()

When three arguments are supplied, np.where() returns values from the second argument where the condition is True and values from the third argument otherwise.

import numpy as np marks = np.array([35, 55, 78, 29, 91]) status = np.where(marks >= 40, "Pass", "Fail") print(status)

Output:

['Fail' 'Pass' 'Pass' 'Fail' 'Pass']

Replace Values Based on a Condition

import numpy as np temperatures = np.array([18, 26, 31, 22, 35]) adjusted = np.where(temperatures < 25, 25, temperatures) print(adjusted)

Output:

[25 26 31 25 35]

In this example, values below 25 are replaced with 25, while all other values remain unchanged.

Tip: np.where() returns a new result. It does not modify the original array unless you explicitly assign the result back to that array.

3. Understanding np.select()

The np.select() function is useful when there are multiple conditions and each condition needs a different output value. It accepts a list of conditions, a corresponding list of choices, and an optional default value.

import numpy as np marks = np.array([92, 76, 58, 35, 84]) conditions = [ marks >= 85, marks >= 70, marks >= 40 ] choices = [ "Excellent", "Good", "Pass" ] result = np.select( conditions, choices, default="Fail" ) print(result)

Output:

['Excellent' 'Good' 'Pass' 'Fail' 'Good']

NumPy checks the conditions in order. When multiple conditions are True for an element, the choice associated with the first matching condition is used.

Important: Arrange overlapping conditions carefully. For example, test marks >= 85 before marks >= 70, otherwise high marks could be classified by the less specific condition first.

4. Applying Multiple Conditions with np.select()

Multiple conditions can classify data into categories. This is useful for grading, pricing rules, performance levels, and threshold-based data processing.

import numpy as np sales = np.array([1200, 750, 450, 1800, 300]) conditions = [ sales >= 1500, sales >= 700, sales >= 400 ] choices = [ "High", "Medium", "Low" ] category = np.select( conditions, choices, default="Very Low" ) print(category)

Output:

['Medium' 'Medium' 'Low' 'High' 'Very Low']
Sales Range Category
1,500 and aboveHigh
700 to 1,499Medium
400 to 699Low
Below 400Very Low

The conditions are evaluated in their listed order, so the first matching choice determines the output for each element.

5. Introduction to np.nonzero()

The np.nonzero() function returns the indices of elements that are not equal to zero. For a one-dimensional array, it returns a tuple containing one index array.

import numpy as np values = np.array([0, 10, 0, 25, 40, 0, 15]) indices = np.nonzero(values) print("Nonzero indices:", indices[0]) print("Nonzero values:", values[indices])

Output:

Nonzero indices: [1 3 4 6] Nonzero values: [10 25 40 15]

Every nonzero element is included, regardless of whether it is positive or negative.

import numpy as np values = np.array([-5, 0, 8, 0, -2]) print(np.nonzero(values)[0])

Output:

[0 2 4]

6. Finding Nonzero Positions in Two-Dimensional Arrays

For multidimensional arrays, np.nonzero() returns one index array for each dimension. These arrays describe the coordinates of every nonzero element.

import numpy as np matrix = np.array([ [0, 5, 0], [7, 0, 9], [0, 3, 4] ]) row_indices, column_indices = np.nonzero(matrix) print("Rows:", row_indices) print("Columns:", column_indices) print("Values:", matrix[row_indices, column_indices])

Output:

Rows: [0 1 1 2 2] Columns: [1 0 2 1 2] Values: [5 7 9 3 4]
Finding Nonzero Matrix Coordinates Matrix 0 5 0 7 0 9 0 3 4 Nonzero Coordinates Rows: [0, 1, 1, 2, 2] Columns: [1, 0, 2, 1, 2] Values: [5, 7, 9, 3, 4]

Each nonzero element has a row coordinate and a column coordinate.

7. Counting Nonzero Elements

The np.count_nonzero() function counts elements that are not equal to zero. You can count all nonzero elements or count them along a specified axis.

import numpy as np matrix = np.array([ [0, 2, 3], [4, 0, 6], [0, 8, 0] ]) print("Total nonzero:", np.count_nonzero(matrix)) print("Nonzero per row:", np.count_nonzero(matrix, axis=1)) print("Nonzero per column:", np.count_nonzero(matrix, axis=0))

Output:

Total nonzero: 6 Nonzero per row: [2 2 1] Nonzero per column: [1 2 2]
Expression Meaning
np.count_nonzero(array) Counts all nonzero elements.
np.count_nonzero(array, axis=0) Counts nonzero values in each column.
np.count_nonzero(array, axis=1) Counts nonzero values in each row.

8. Understanding np.argwhere()

The np.argwhere() function returns the coordinates of elements satisfying a condition, arranged as rows in a two-dimensional array. It is convenient when you want each coordinate grouped together.

import numpy as np matrix = np.array([ [10, 0, 30], [0, 50, 60], [70, 0, 0] ]) positions = np.argwhere(matrix > 40) print(positions)

Output:

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

Each output row contains the coordinates of one matching element. For example, coordinate [1, 1] refers to the value 50.

Remember: np.nonzero() returns a tuple of index arrays, while np.argwhere() returns an array of grouped coordinates. Choose the form that best fits your task.

9. Comparing Where, Select, Nonzero, and Argwhere

Function Main Purpose Typical Result
np.where() Return condition-based indices or choose between alternatives. Indices or selected values.
np.select() Choose results from multiple conditions. Array of selected values.
np.nonzero() Locate elements that are not zero. Tuple of index arrays.
np.count_nonzero() Count nonzero elements. Integer or array of counts.
np.argwhere() Return coordinates of elements satisfying a condition. Array of grouped coordinates.
Choosing the right function: Use np.where() for a condition and two alternatives, np.select() for several conditions, np.nonzero() for nonzero positions, and np.count_nonzero() when you only need a count.

10. Practical Project: Student Result Classification

In this project, student marks will be classified into result categories using np.select(). We will also locate students who meet a target score using np.where().

import numpy as np students = np.array(["Samadhan", "Pradnya", "Samiksha"]) marks = np.array([68, 92, 37]) conditions = [ marks >= 85, marks >= 40 ] choices = [ "Excellent", "Pass" ] results = np.select( conditions, choices, default="Fail" ) target_indices = np.where(marks >= 70)[0] print("Student results:") for name, mark, result in zip(students, marks, results): print(name, "- Marks:", mark, "- Result:", result) print("Students scoring at least 70:") print(students[target_indices])

Output:

Student results: Samadhan - Marks: 68 - Result: Pass Pradnya - Marks: 92 - Result: Excellent Samiksha - Marks: 37 - Result: Fail Students scoring at least 70: ['Pradnya']

Project Learning Outcomes

  • Classify data using multiple conditions.
  • Find qualifying records using np.where().
  • Keep names and marks aligned using matching indices.
  • Use vectorized operations instead of manually checking every mark.

11. Common Mistakes and Best Practices

Using np.where() for Multiple Categories

Nested np.where() expressions can become difficult to read. Use np.select() when several conditions map to different choices.

Ignoring Condition Order

np.select() uses the choice corresponding to the first True condition. Put more specific or higher-priority conditions first.

Confusing Nonzero Values with Positive Values

np.nonzero() includes negative values as well as positive values. It excludes zero, not negative numbers.

Confusing Coordinate Formats

np.nonzero() returns one index array per dimension, while np.argwhere() groups coordinates into rows.

Forgetting Array Shapes

Ensure conditions and choices are compatible with the array shapes. NumPy uses broadcasting where supported, but incompatible shapes can raise an error.

12. Practice Exercises

Exercise 1: Find Matching Indices

Create an array of integers and use np.where() to find the indices of values greater than 50.

Exercise 2: Conditional Replacement

Use np.where() to replace all negative values in an array with zero.

Exercise 3: Multiple Categories

Use np.select() to classify marks as Excellent, Pass, or Fail.

Exercise 4: Nonzero Positions

Create an array containing zero and nonzero values. Use np.nonzero() to find all nonzero positions.

Exercise 5: Matrix Coordinates

Create a two-dimensional array and use np.argwhere() to find coordinates of values greater than 25.

Exercise 6: Count Nonzero Elements

Use np.count_nonzero() to count nonzero values in the complete matrix and separately in each row.

Summary

In this lesson, you learned to use np.where() to find matching indices and choose values based on a condition. You also explored np.select() for multiple conditional choices and learned how condition order affects the selected result.

You practiced locating nonzero elements with np.nonzero(), counting them with np.count_nonzero(), and retrieving grouped coordinates with np.argwhere(). These functions help classify, filter, locate, and analyze values efficiently in one-dimensional and multidimensional arrays.