NumPy Tutorial – Python Library
NumPy is a powerful library for numerical computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. NumPy’s array objects are more memory-efficient and perform better than Python lists, which is essential for tasks in scientific computing, data analysis, and machine learning. This NumPy tutorial will cover core features, and all concept from basic to advanced divided in 10 sections.
Section 1: NumPy Arrays
The numpy array also called ndarray is a grid of values, all of the same types. They can be one-dimensional (like a list), two-dimensional (like a matrix) or multi-dimensional (like a table with rows and columns).
To understand all the basics of Numpy Arrays – explaining their types (one-dimensional and multi-dimensional), key attributes (axis, shape, rank, dtype): Basics of Numpy Arrays
Section 2: Creating Arrays in Numpy
NumPy arrays are created using the np.array()
function, which converts lists, tuples, or other sequences into a NumPy array. You can create different types of arrays, such as 1D arrays from a simple list of elements, 2D arrays from nested lists representing rows and columns, and multi-dimensional arrays by further nesting lists.
Example of a simple one-dimensional array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output
[1 2 3 4 5]
To understand all ways for creating Array refer to: Numpy array creation page. For understanding techniques in-depth ( explained in numpy creation page ) refer to following resources:
- arange Method – Creates an array with evenly spaced values within a specified range.
- zero Method – Creates an array filled with zeros.
- array filled with all ones
- inspace Method – array of evenly spaced values over a specified interval.
- eye Method – 2D array with ones on the diagonal and zeros elsewhere (identity matrix)
- create an empty and a full NumPy array
Note: These numPy array creation methods form the foundation for efficiently working with arrays in data science, machine learning, and scientific computing.
Section 4: Operations in Numpy Array
NumPy arrays offer four essential types of operations that allow efficient data manipulation by performing element-wise computations, mathematical functions, string processing, and logical comparisons.
- Binary Operations Perform element-wise comparisons (e.g., greater than, equal to) and logical operations like AND or OR.
- Mathematical Operations – Functions such as
sum()
,mean()
, andsqrt()
allow for quick and efficient numerical calculations.- String Operations– Use
np.char()
functions for operations like concatenation, uppercasing, and replacing strings within arrays.- Arithmetic Operations – Enable fast element-wise addition, subtraction, multiplication, and division in Arrays.
Section 5: Slicing & Indexing in Numpy Array
While indexing is used to access specific elements in an array based on their positions or conditions, slicing is used to extract a subset of elements from an array using the syntax array[start:stop:step]
. It works for both 1D and multi-dimensional arrays, making it easy to select specific rows, columns, or ranges of data.
Section 6: Shaping & Reshaping in Array
Shape of an array can be defined as the number of elements in each dimension. It can be accessed using the shape
attribute, which returns a tuple representing the dimensions of the array. In this section, we will explore how to change the shape of a NumPy array. This includes reshaping, flattening, and modifying the structure of arrays to suit specific tasks.
Section 7: Sorting and Searching in Array
Sorting in NumPy refers to arranging the elements of an array in a specific order, either ascending or descending. The np.sort()
function is used for this purpose. By default, it sorts elements in ascending order, and descending order can be achieved using slicing techniques like [::-1]
.
Note: Sorting works for both single-dimensional and multi-dimensional arrays, click on links belows for in-depth understanding:
Searching in NumPy involves finding specific values or conditions within an array. In this section, we’ll explore different techniques for searching within NumPy arrays searching for Specific Values using np.where() , np.searchsorted()
and np.nonzero()
that returns the indices of all non-zero elements.
- Dive deeper with Seraching in Numpy Array
- Numpy Array – Searching , Sorting , Counting
Section 8: Combining, Splitting, and Aggregating Arrays
Combining arrays involves merging smaller arrays into a single larger one. arrays can be combined vertically, horizontally, or along any specific axis. It include Techniques like concatenation and stacking ( horizontal , vertical ).
Splitting arrays is the process of dividing a larger array into smaller, manageable sub-arrays. The division can occur along rows, columns, or other axes.
Aggregation refers to summarizing data within an array by applying mathematical operations like summing, finding the average, or determining the maximum/minimum values.
- Summing Function- In this we use numpy.sum() to do the sum of array elements.
- Average Function – In this we use numpy.mean() to find out the average of array elements.
Section 9: Matrix Operations
In NumPy, a matrix is represented as a 2D array. Matrix operations are a fundamental part of linear algebra. Matrix Addition, Subtraction, and Multiplication are fundamental for manipulating matrices. To work with matrices, NumPy provides simple tools. For example, np.transpose()
flips the matrix by turning rows into columns and columns into rows. If you want to change the shape of a matrix, like turning a single row into multiple rows, you use np.reshape()
. To simplify a matrix and turn it into a single list of values, you can use np.flatten()
. Finally, np.dot()
is used for multiplying two matrices.
- To learn more about the Matrix Operations in Numpy: Matrix Addition, Subtraction, and Multiplication. Now, there are many more matrix operations like:
- Matrix Transpose
- Determinant and Inverse of a Matrix
- Matrix Operation – calculating dot product of two vectors
- Find variance of a matrix
Section 10: Linear Algebra in Numpy Array
Eigenvalues and eigenvectors are fundamental concepts in linear algebra. NumPy provides a robust numpy.linalg
module to perform various linear algebra operations efficiently.
Section 11: Numpy and Random Data
NumPy provides a powerful module, numpy.random
, for generating random data efficiently enables users to create random numbers, samples, and arrays for a variety of distributions.
The module allows for generating random integers, random floats between 0 and 1 and random samples from normal, uniform, and other statistical distributions. For example: if you want to generate 5 random numbers from the normal distribution using NumPy. Click on the link for solution.
Section 12: Advance Numpy
Welcome to the advanced section of NumPy! If you’ve already learned the basics of arrays, you’re ready to explore some powerful tools that make working with data faster and easier
- Numpy Array Broadcasting– Broadcasting lets you do operations on arrays of different shapes without changing their size or shape.
- Numpy Array Vectorization – Instead of using slow loops, vectorization uses optimized functions to work on the whole array at once
- Universal Fuction in Numpy– Ufuncs are built-in functions in NumPy that perform operations on each element of an array. Example: n
p.add()
for addition,np.sqrt()
for square root, andnp.sin()
for sine values.- Working With Images in numpy– In NumPy, you can treat images as multi-dimensional arrays (like 2D or 3D arrays).
Refer to Practice Exercises, Questions, and Solutions for hands-on-numpy problems