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

Array Inspection and Attributes

Learn how to inspect NumPy arrays, understand their structure, examine data types, and retrieve important information without manually checking every element.

1. Learning Objectives

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

  • Inspect the shape and dimensions of an array.
  • Find the total number of elements in an array.
  • Identify the data type and memory usage of array elements.
  • Use attributes such as ndim, shape, size, and dtype.
  • Use np.info() and basic inspection techniques when needed.
  • Debug common array structure problems efficiently.

2. What Is Array Inspection?

Array inspection means examining the properties and structure of a NumPy array. Before performing calculations, it is often useful to know how many dimensions an array has, how its elements are arranged, and what type of data it stores.

NumPy provides attributes that return this information directly. These attributes help developers understand arrays without writing loops to count or examine individual elements.

Example: A Student Marks Array

import numpy as np marks = np.array([ [78, 85, 90], [88, 76, 92] ]) print(marks)

The array contains marks for two students across three subjects.

marks array 78 85 90 88 76 92 Row 0 Row 1 Column 0 Column 1 Column 2

The array has two rows, three columns, and six total elements.

3. Important NumPy Array Attributes

NumPy arrays provide several built-in attributes. These are accessed without parentheses because they are attributes rather than methods.

Attribute Purpose Example Result
ndim Returns the number of dimensions. 2
shape Returns the length of the array along each dimension. (2, 3)
size Returns the total number of elements. 6
dtype Returns the data type of the elements. int64 or another integer type
itemsize Returns the size in bytes of one array element. 8 for an 8-byte element
nbytes Returns the total bytes used by the array elements. 48 for six 8-byte elements
Tip: The exact integer data type can vary depending on the platform and how the array was created. Check dtype instead of assuming that every integer array uses the same type.

4. Inspecting Dimensions with ndim

The ndim attribute tells you how many dimensions an array has. It is useful when working with data that may be one- dimensional, two-dimensional, or higher-dimensional.

import numpy as np one_d = np.array([10, 20, 30]) two_d = np.array([ [10, 20, 30], [40, 50, 60] ]) three_d = np.array([ [[1, 2], [3, 4]], [[5, 6], [7, 8]] ]) print(one_d.ndim) # 1 print(two_d.ndim) # 2 print(three_d.ndim) # 3
Array Dimensions Explanation
[10, 20, 30] 1 A single sequence of elements.
[[10, 20], [30, 40]] 2 Rows and columns.
[[[1, 2]]] 3 A structure with three axes.

5. Understanding Array Shape

The shape attribute returns a tuple describing the number of elements along each dimension. For a two-dimensional array, the tuple is expressed as (rows, columns).

import numpy as np marks = np.array([ [78, 85, 90], [88, 76, 92] ]) print(marks.shape) # (2, 3) print("Rows:", marks.shape[0]) # 2 print("Columns:", marks.shape[1]) # 3
Shape = (2, 3) 3 columns 3 columns Row 0 Row 1 2 rows × 3 columns = 6 elements

For a two-dimensional array, shape is reported as (rows, columns).

Common mistake: Do not confuse shape with size. The shape (2, 3) describes the array's structure, while the size 6 counts its elements.

6. Counting Elements with size

The size attribute returns the total number of elements in an array, regardless of the number of dimensions.

import numpy as np values = np.array([ [10, 20, 30], [40, 50, 60] ]) print(values.size) # 6 single_value = np.array([100]) print(single_value.size) # 1 empty_array = np.array([]) print(empty_array.size) # 0
Remember: For a non-empty rectangular array, the total element count is the product of its dimensions. For example, shape (2, 3) gives 2 × 3 = 6 elements.

7. Checking Data Types with dtype

The dtype attribute identifies the type used to represent elements in the array. NumPy uses this information to perform calculations and manage storage.

import numpy as np integers = np.array([10, 20, 30]) decimals = np.array([10.5, 20.5, 30.5]) labels = np.array(["Samadhan", "Pradnya", "Samiksha"]) print(integers.dtype) print(decimals.dtype) print(labels.dtype)

The exact displayed type may vary by platform and NumPy version. Integer arrays commonly display an integer type, decimal arrays commonly display a floating-point type, and text arrays use a suitable string type.

Why dtype Matters

  • It helps determine which operations are appropriate.
  • It affects the memory required for each element.
  • It helps identify unexpected conversions in calculations.
  • It is useful when importing data from external files.

8. Understanding itemsize and nbytes

NumPy also provides attributes for inspecting memory usage. itemsize reports the bytes used by one element, while nbytes reports the total bytes occupied by the array's element data.

import numpy as np values = np.array([10, 20, 30, 40], dtype=np.int32) print(values.itemsize) # 4 print(values.nbytes) # 16

In this example, each int32 element uses four bytes. Four elements therefore use sixteen bytes for their element data.

Important: nbytes describes the array element buffer, not all Python object overhead or every allocation associated with the array.

9. Using Multiple Attributes Together

In real applications, developers often inspect several attributes together to understand a dataset before processing it.

import numpy as np marks = np.array([ [78, 85, 90], [88, 76, 92] ], dtype=np.int32) print("Array:") print(marks) print("Dimensions:", marks.ndim) print("Shape:", marks.shape) print("Total elements:", marks.size) print("Data type:", marks.dtype) print("Bytes per element:", marks.itemsize) print("Total element bytes:", marks.nbytes)

Typical output for this explicitly typed array is:

Array: [[78 85 90] [88 76 92]] Dimensions: 2 Shape: (2, 3) Total elements: 6 Data type: int32 Bytes per element: 4 Total element bytes: 24
Best practice: Inspect an array's shape and data type before applying operations that require a particular structure or numeric representation.

10. Practical Activity

Activity: Inspect Student Marks

Samadhan, Pradnya, and Samiksha are reviewing a marks dataset. Create a NumPy array containing three students and four subject marks for each student.

Tasks:

  1. Create a two-dimensional integer array with three rows and four columns.
  2. Display the array.
  3. Print its number of dimensions using ndim.
  4. Print its shape and total number of elements.
  5. Display its data type and total element bytes.

Sample Solution

import numpy as np marks = np.array([ [78, 85, 90, 82], [88, 76, 92, 80], [91, 87, 84, 95] ], dtype=np.int32) print("Marks:") print(marks) print("Dimensions:", marks.ndim) print("Shape:", marks.shape) print("Total elements:", marks.size) print("Data type:", marks.dtype) print("Total element bytes:", marks.nbytes)

Expected key results:

  • Dimensions: 2
  • Shape: (3, 4)
  • Total elements: 12
  • Data type: int32
  • Total element bytes: 48

11. Common Mistakes to Avoid

Mistake Correct Approach
Writing array.shape() Use array.shape because shape is an attribute.
Assuming shape and size mean the same thing Use shape for dimensions and size for element count.
Assuming all integer arrays use the same dtype Inspect array.dtype or specify a dtype explicitly.
Assuming nbytes includes all Python memory overhead Remember that nbytes measures the element data buffer.
Inspecting only the printed values Check shape, ndim, dtype, and size when structure matters.

Summary

Array inspection is an essential step in working with NumPy. Attributes provide quick information about an array's dimensions, structure, element count, data type, and element memory usage.

  • ndim returns the number of dimensions.
  • shape returns the size along each dimension.
  • size returns the total number of elements.
  • dtype identifies the element data type.
  • itemsize returns bytes per element.
  • nbytes returns total bytes used by element data.