1
What is NumPy?
NumPy (Numerical Python) is a fundamental Python library used for scientific computing, numerical calculations, and working with multi-dimensional arrays.
NumPy arrays are significantly faster, memory-efficient, and optimized compared to standard Python lists.
Python List
Stores pointers to objects scattered in memory. Slower execution.
NumPy ndarray
Continuous contiguous memory blocks (C-style). Ultra-fast SIMD operations.
PYTHON • VERSION CHECK
import numpy as np /* Check installed NumPy version */ print("NumPy Version:", np.__version__)
Expected Output
NumPy Version: 1.26.4
2
Creating an Array
Definition:
np.array() function is used to create a NumPy array from a Python list or tuple.
Important Note: NumPy arrays hold homogeneous data (elements of the same data type). If you pass mixed data types (like numbers and strings), NumPy automatically upcasts/type-casts everything to a common string type!
PYTHON • ARRAY CREATION
import numpy as np /* Mixed data type causes string upcasting */ arr = np.array([10, 20, 30, 40, 50, "gagan"]) print("Array:") print(arr) print("Data Type:", arr.dtype)
Expected Output
Array:['10' '20' '30' '40' '50' 'gagan']
Data Type: <U11
3
1D Array (One-Dimensional)
Definition: A 1D array contains elements arranged in a single linear line. It has only 1 axis (Axis 0).
Visual 1D Array Structure
10
20
30
40
50
Index: [0] [1] [2] [3] [4]
PYTHON • 1D ARRAY
import numpy as np arr_1d = np.array([10, 20, 30, 40, 50]) print("1D Array:") print(arr_1d) print("Dimension (ndim):", arr_1d.ndim) print("Shape:", arr_1d.shape)
Expected Output
1D Array:[10 20 30 40 50]
Dimension (ndim): 1
Shape: (5,)
4
2D Array (Two-Dimensional)
Definition: A 2D array contains data organized in rows and columns (like a table, matrix, or spreadsheet).
Visual 2D Matrix Structure (2 Rows x 3 Columns)
10
20
30
40
50
60
PYTHON • 2D ARRAY
import numpy as np arr_2d = np.array([ [10, 20, 30], [40, 50, 60] ]) print("2D Array:") print(arr_2d) print("Dimension:", arr_2d.ndim) print("Shape (Rows, Cols):", arr_2d.shape)
Expected Output
2D Array:[[10 20 30]
[40 50 60]]
Dimension: 2
Shape (Rows, Cols): (2, 3)
5
3D Array (Three-Dimensional)
Definition: A 3D array consists of multiple 2D arrays (layers / matrices).
Structure formula:
Structure formula:
Layers x Rows x Columns
PYTHON • 3D ARRAY
import numpy as np arr_3d = np.array([ [ [1, 2, 3], [4, 5, 6] ], [ [7, 8, 9], [10, 11, 12] ] ]) print("3D Array:") print(arr_3d) print("Dimension:", arr_3d.ndim) print("Shape (Layers, Rows, Cols):", arr_3d.shape)
Expected Output
3D Array:[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
Dimension: 3
Shape (Layers, Rows, Cols): (2, 2, 3)
6
Array Properties
Definition: NumPy attributes provide meta-information about the structure, memory, and data format of an array.
ndim: Number of dimensions (axes).shape: Tuple representing the dimensions of array (e.g. (2, 3)).size: Total number of elements in the array.dtype: Data type of elements (int64, float64, etc.).
PYTHON • ARRAY ATTRIBUTES
import numpy as np arr = np.array([ [10, 20, 30], [40, 50, 60] ]) print("ndim:", arr.ndim) print("shape:", arr.shape) print("size:", arr.size) print("dtype:", arr.dtype)
Expected Output
ndim: 2shape: (2, 3)
size: 6
dtype: int32 (or int64 depending on OS)
7
Array Indexing (1D & 2D)
Definition: Indexing is used to access a specific element from an array using zero-based indices.
Syntax for 2D:
Syntax for 2D:
array[row_index, column_index]
PYTHON • INDEXING EXAMPLES
import numpy as np /* 1D Indexing */ arr_1d = np.array([10, 20, 30, 40, 60]) print("First element:", arr_1d[0]) print("Last element (Negative):", arr_1d[-1]) /* 2D Indexing */ arr_2d = np.array([ [10, 20, 30], [40, 50, 60] ]) print("Row 0, Col 0:", arr_2d[0, 0]) print("Row 1, Col 2:", arr_2d[1, 2])
Expected Output
First element: 10Last element (Negative): 60
Row 0, Col 0: 10
Row 1, Col 2: 60
8
Array Slicing (1D & 2D)
Definition: Slicing extracts a range of elements from an array.
Syntax:
2D Syntax:
Syntax:
array[start : stop : step]
2D Syntax:
array[row_start:row_stop, col_start:col_stop]
PYTHON • SLICING DEMO
import numpy as np arr = np.array([10, 20, 30, 40, 50]) print("Step Slicing (every 2nd):", arr[0:5:2]) print("Reversed Array:", arr[::-1]) /* 2D Matrix Slicing */ arr_2d = np.array([ [10, 20, 30], [40, 50, 60], [70, 80, 90] ]) /* Extract submatrix: Rows 0 to 1, Cols 1 to 2 */ print("2D Sliced Submatrix:") print(arr_2d[0:2, 1:3])
Expected Output
Step Slicing (every 2nd): [10 30 50]Reversed Array: [50 40 30 20 10]
2D Sliced Submatrix:
[[20 30]
[50 60]]
9
Reshape
Definition:
Constraint: The total number of elements must remain identical before and after reshaping!
reshape() changes the shape (dimensions) of an array without modifying its data.
Constraint: The total number of elements must remain identical before and after reshaping!
PYTHON • RESHAPE
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) new_arr = arr.reshape(2, 3) print("Original 1D:", arr) print("Reshaped 2D (2x3):") print(new_arr)
Expected Output
Original 1D: [1 2 3 4 5 6]Reshaped 2D (2x3):
[[1 2 3]
[4 5 6]]
10
Flatten
Definition:
flatten() converts a multi-dimensional array into a 1-dimensional array.
flatten() always returns a copy (occupies new memory).
PYTHON • FLATTEN
import numpy as np arr = np.array([ [1, 2, 3], [4, 5, 6] ]) flat_arr = arr.flatten() print("Flattened 1D Array:", flat_arr)
Expected Output
Flattened 1D Array: [1 2 3 4 5 6]
11
Ravel (ravel vs flatten)
Definition:
Key Difference:
ravel() converts a multi-dimensional array into a 1D array.
Key Difference:
flatten() returns a copy (separate memory), whereas ravel() returns a view (shares same memory) whenever possible!
PYTHON • RAVEL DEMO
import numpy as np arr = np.array([ [1, 2, 3], [4, 5, 6] ]) ravel_arr = arr.ravel() print("Ravel 1D Array:", ravel_arr)
Expected Output
Ravel 1D Array: [1 2 3 4 5 6]
12
Array Operations (Vectorized & Scalar)
Definition: NumPy performs element-wise operations directly on arrays without requiring explicit
for loops.
PYTHON • ELEMENT-WISE & SCALAR MATH
import numpy as np a = np.array([10, 20, 30]) b = np.array([1, 2, 3]) print("Addition (a + b):", a + b) print("Subtraction (a - b):", a - b) print("Multiplication (a * b):", a * b) print("Division (a / b):", a / b) print("Power (a ** 2):", a ** 2) /* Scalar Operations */ arr = np.array([10, 20, 30]) print("Scalar Multiply (arr * 2):", arr * 2)
Expected Output
Addition (a + b): [11 22 33]Subtraction (a - b): [9 18 27]
Multiplication (a * b): [10 40 90]
Division (a / b): [10. 10. 10.]
Power (a ** 2): [100 400 900]
Scalar Multiply (arr * 2): [20 40 60]
13
Comparison Operations
Definition: Compares every element in the array against a condition and returns a Boolean array of
True / False values.
PYTHON • COMPARISON
import numpy as np arr = np.array([10, 20, 30, 40, 50]) print("arr > 25:", arr > 25) print("arr == 30:", arr == 30)
Expected Output
arr > 25: [False False True True True]arr == 30: [False False True False False]
14
Axis Concept (Axis=0 vs Axis=1)
Definition:
For a 2D Array:
• axis=0: Operation across rows (Downwards / Column-wise sum)
• axis=1: Operation across columns (Horizontal / Row-wise sum)
axis specifies the direction of operations in multi-dimensional arrays.
For a 2D Array:
• axis=0: Operation across rows (Downwards / Column-wise sum)
• axis=1: Operation across columns (Horizontal / Row-wise sum)
axis=0 (Column-Wise)
↓ Moves Down Rows
Sum of col 0, col 1, col 2
axis=1 (Row-Wise)
→ Moves Across Columns
Sum of row 0, row 1
PYTHON • AXIS DEMO
import numpy as np arr = np.array([ [10, 20, 30], [40, 50, 60] ]) print("Sum axis=0 (Column-wise):", np.sum(arr, axis=0)) print("Sum axis=1 (Row-wise):", np.sum(arr, axis=1))
Expected Output
Sum axis=0 (Column-wise): [50 70 90]Sum axis=1 (Row-wise): [60 150]
15
Mathematical & Statistical Functions
Definition: Built-in statistical and mathematical functions for fast aggregations.
PYTHON • STATS FUNCTIONS
import numpy as np arr = np.array([10, 20, 30, 40, 50]) print("Sum:", np.sum(arr)) print("Mean:", np.mean(arr)) print("Min:", np.min(arr)) print("Max:", np.max(arr)) print("Std Dev:", np.std(arr)) print("Variance:", np.var(arr)) print("Median:", np.median(arr))
Expected Output
Sum: 150Mean: 30.0
Min: 10
Max: 50
Std Dev: 14.142135623730951
Variance: 200.0
Median: 30.0
16
Boolean Indexing / Filtering
Definition: Extracting array elements that satisfy specific conditional logic using bitwise operators
& (AND), | (OR).
PYTHON • BOOLEAN FILTERING
import numpy as np arr = np.array([10, 20, 30, 40, 50]) /* Single Condition */ result = arr[arr > 25] print("Elements > 25:", result) /* Multiple Conditions (&) */ result_multi = arr[(arr > 20) & (arr < 50)] print("20 < Elements < 50:", result_multi)
Expected Output
Elements > 25: [30 40 50]20 < Elements < 50: [30 40]
17
np.where()
Definition:
np.where() finds the index positions where a condition is True.
PYTHON • NP.WHERE
import numpy as np arr = np.array([10, 20, 30, 40, 50]) result = np.where(arr > 25) print("Indices where arr > 25:", result)
Expected Output
Indices where arr > 25: (array([2, 3, 4]),)
18
Combining Arrays (Concatenate, vstack, hstack)
Definition: Joining multiple arrays together.
•
•
•
•
concatenate(): Joins arrays along specified axis.
•
vstack(): Stacks arrays vertically (row-wise).
•
hstack(): Stacks arrays horizontally (column-wise).
PYTHON • STACKING & CONCATENATION
import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) print("Concatenate:", np.concatenate((a, b))) print("Vertical Stack (vstack):") print(np.vstack((a, b))) print("Horizontal Stack (hstack):", np.hstack((a, b)))
Expected Output
Concatenate: [1 2 3 4 5 6]Vertical Stack (vstack):
[[1 2 3]
[4 5 6]]
Horizontal Stack (hstack): [1 2 3 4 5 6]
19
Sorting
Definition:
np.sort() sorts array elements in ascending order. Use slice [::-1] for descending order.
PYTHON • SORTING
import numpy as np arr = np.array([50, 10, 40, 20, 30]) print("Ascending:", np.sort(arr)) print("Descending:", np.sort(arr)[::-1])
Expected Output
Ascending: [10 20 30 40 50]Descending: [50 40 30 20 10]
20
Unique Values & Counts
Definition:
np.unique() extracts distinct elements. Setting return_counts=True returns frequency counts.
PYTHON • UNIQUE VALUES
import numpy as np arr = np.array([10, 20, 20, 30, 30, 30, 40]) values, counts = np.unique(arr, return_counts=True) print("Unique Values:", values) print("Frequency Counts:", counts)
Expected Output
Unique Values: [10 20 30 40]Frequency Counts: [1 2 3 1]
21
Broadcasting
Definition: Broadcasting allows NumPy to perform arithmetic operations on arrays of different/compatible shapes automatically without memory duplication.
PYTHON • BROADCASTING
import numpy as np arr = np.array([ [10, 20, 30], [40, 50, 60] ]) result = arr + 10 print("2D Broadcasting (+10):") print(result)
Expected Output
2D Broadcasting (+10):[[20 30 40]
[50 60 70]]
22
Copy (Deep Copy)
Definition:
copy() creates a separate, independent duplicate array in memory. Modifying the copy does NOT affect the original array.
PYTHON • COPY
import numpy as np arr = np.array([10, 20, 30]) new_arr = arr.copy() new_arr[0] = 100 print("Original:", arr) print("Copy:", new_arr)
Expected Output
Original: [10 20 30]Copy: [100 20 30]
23
View (Shallow View)
Definition:
view() creates a new array object pointing to the SAME underlying memory buffer. Modifying the view WILL alter the original array!
PYTHON • VIEW
import numpy as np arr = np.array([10, 20, 30]) new_arr = arr.view() new_arr[0] = 100 print("Original (Modified!):", arr) print("View:", new_arr)
Expected Output
Original (Modified!): [100 20 30]View: [100 20 30]
24
Random Arrays
Definition:
np.random module generates random numbers, matrices, and distributions.
PYTHON • RANDOM GENERATION
import numpy as np /* Random integers between 10 and 100 */ arr_int = np.random.randint(10, 100, 5) /* Random decimals between 0 and 1 */ arr_float = np.random.rand(5) /* Random 2D matrix (3x4) */ arr_2d_rand = np.random.randint(1, 10, size=(3, 4)) print("Random Integers:", arr_int) print("Random Decimals:", arr_float) print("Random 2D Matrix:") print(arr_2d_rand)
Expected Output (Values vary)
Random Integers: [45 88 12 73 91]Random Decimals: [0.12 0.84 0.53 0.39 0.77]
Random 2D Matrix:
[[4 8 2 9]
[1 7 5 3]
[6 2 8 4]]
25
NumPy + Pandas Integration
Definition: Convert Pandas DataFrames/Series into native NumPy arrays using
to_numpy() for high-performance numerical operations.
PYTHON • PANDAS TO NUMPY
import numpy as np import pandas as pd df = pd.DataFrame({ "Name": ["A", "B", "C"], "Age": [20, 25, 30] }) /* Series to NumPy */ age_array = df["Age"].to_numpy() /* Full DataFrame to NumPy */ data_array = df.to_numpy() print("Age NumPy Array:", age_array) print("DataFrame to Array:") print(data_array)
Expected Output
Age NumPy Array: [20 25 30]DataFrame to Array:
[['A' 20]
['B' 25]
['C' 30]]
26
Quick Revision & Cheatsheet
| Concept / Function | Syntax | Key Purpose / Behavior |
|---|---|---|
| 1D Array | np.array([1, 2, 3]) |
Single axis linear list |
| 2D Array | np.array([[1, 2], [3, 4]]) |
Matrix (Rows x Columns) |
| Array Shape | arr.shape |
Dimensions tuple (Rows, Cols) |
| Reshape | arr.reshape(r, c) |
Changes array dimensions |
| Flatten vs Ravel | arr.flatten() / arr.ravel() |
Flatten returns copy, Ravel returns view |
| Axis 0 vs Axis 1 | axis=0 (Rows down) / axis=1 (Cols across) |
Direction of mathematical aggregation |
| Boolean Indexing | arr[arr > 25] |
Filtering elements by condition |
| Combining Arrays | np.vstack() / np.hstack() |
Vertical vs Horizontal stacking |
| Copy vs View | arr.copy() / arr.view() |
Independent memory vs shared memory view |