Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

NumPy: Numerical Computing

Lesson 25 of 37 in the free Data Science notes on Siksha Sarovar, written by Rohit Jangra.

NumPy (Numerical Python)

Definition: NumPy is the foundational library for numerical computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a vast collection of high-level mathematical functions to operate on these arrays efficiently.

import numpy as np

---

Why NumPy?

FeaturePython ListsNumPy Arrays
SpeedSlow (interpreted loops)Fast (C-based, vectorized)
MemoryMore memory per elementCompact storage
OperationsElement-by-element loops neededVectorized (whole-array operations)
Data TypesMixed types allowedHomogeneous (single type)
BroadcastingNot supportedSupported

NumPy arrays are up to 50x faster than Python lists for numerical operations.

---

Creating Arrays

MethodCodeResult
From listnp.array([1, 2, 3])[1 2 3]
Zerosnp.zeros((2, 3))2×3 matrix of zeros
Onesnp.ones((3, 3))3×3 matrix of ones
Rangenp.arange(0, 10, 2)[0 2 4 6 8]
Linspacenp.linspace(0, 1, 5)[0 0.25 0.5 0.75 1]
Randomnp.random.rand(3, 3)3×3 random values (0 to 1)
Identitynp.eye(3)3×3 identity matrix
Fullnp.full((2, 2), 7)2×2 matrix filled with 7

---

Array Properties

PropertyCodeDescription
shapearr.shapeDimensions (e.g., (3, 4))
ndimarr.ndimNumber of dimensions
sizearr.sizeTotal number of elements
dtypearr.dtypeData type (int64, float64)
itemsizearr.itemsizeBytes per element

---

Array Operations (Vectorized)

NumPy performs operations on entire arrays without loops — this is called vectorization.

OperationCodeResult
Additiona + bElement-wise addition
Multiplicationa * bElement-wise multiplication
Scalara * 3Multiply all elements by 3
Squarea ** 2Square each element
Square Rootnp.sqrt(a)Square root of each element
Sumnp.sum(a) or a.sum()Sum of all elements
Meannp.mean(a)Average
Std Devnp.std(a)Standard deviation
Min/Maxa.min(), a.max()Minimum, Maximum
Dot Productnp.dot(a, b)Matrix multiplication

---

Indexing and Slicing

arr = np.array([10, 20, 30, 40, 50])
arr[0]      # 10 (first element)
arr[-1]     # 50 (last element)
arr[1:4]    # [20 30 40] (slice)
arr[::2]    # [10 30 50] (every 2nd element)

2D Array Indexing:

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix[0, 0]     # 1 (row 0, col 0)
matrix[1, :]     # [4 5 6] (entire row 1)
matrix[:, 2]     # [3 6 9] (entire column 2)
matrix[0:2, 1:]  # [[2 3], [5 6]] (submatrix)

---

Reshaping Arrays

MethodCodeDescription
Reshapearr.reshape(3, 4)Change shape without changing data
Flattenarr.flatten()Convert to 1D array
Transposearr.TSwap rows and columns

---

Broadcasting

Broadcasting allows NumPy to perform operations on arrays of different shapes by automatically expanding the smaller array.

a = np.array([[1, 2, 3], [4, 5, 6]])  # Shape: (2, 3)
b = np.array([10, 20, 30])             # Shape: (3,)
result = a + b  
# [[11 22 33], [14 25 36]]  — b is broadcast across each row

---

NumPy in Data Science

ApplicationHow NumPy is Used
Linear AlgebraMatrix operations, eigenvalues, SVD
Image ProcessingImages as pixel arrays (H × W × 3)
Machine LearningFeature matrices, weight updates
Statistical AnalysisMean, median, variance, correlations
Signal ProcessingFourier transforms (np.fft)

Summary

  • NumPy is the foundation of numerical computing in Python.
  • Arrays are faster and more memory-efficient than Python lists.
  • Vectorized operations eliminate the need for explicit loops.
  • Broadcasting allows operations on arrays of different shapes.
  • NumPy underpins Pandas, Scikit-learn, TensorFlow, and virtually every DS library.