PYTHON NUMPY ARRAYS & COMPUTATION

Perform lightning-fast numerical computations, matrix manipulation, and vectorized data analysis using NumPy in Python.

🔢 What is NumPy in Python?

NumPy (Numerical Python) is the foundational library for scientific computing, data science, and machine learning in Python. At its core is the ndarray object—a multidimensional array of homogeneous data types that executes up to 50x faster than standard Python lists through optimized C-level vectorization.

1. Basic Array Declaration & Initialization
Import NumPy and create 1D and 2D arrays using np.array().
Python
import numpy as np

# Creating a 1D array
arr_1d = np.array([10, 20, 30, 40, 50])

# Creating a 2D matrix array
matrix_2d = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print("1D Array:\n", arr_1d)
print("\n2D Matrix:\n", matrix_2d)
Output: 1D Array: [10 20 30 40 50] 2D Matrix: [[1 2 3] [4 5 6]]
Real-Time Example 1: Array Attributes (Shape, Dtype, Size)
Inspect metadata attributes like shape, dtype, and size of NumPy arrays.
Python
import numpy as np

sales_data = np.array([
    [450, 1200, 300],
    [850, 950, 1100]
])

print("Array Shape (Rows, Cols):", sales_data.shape)
print("Data Type (Dtype):", sales_data.dtype)
print("Total Element Count:", sales_data.size)
print("Number of Dimensions:", sales_data.ndim)
Output: Array Shape (Rows, Cols): (2, 3) Data Type (Dtype): int64 Total Element Count: 6 Number of Dimensions: 2
Real-Time Example 2: Vectorized Arithmetic Operations
Perform element-wise math operations instantly across entire arrays without writing explicit for loops.
Python
import numpy as np

base_prices = np.array([100, 200, 300, 400])

# Add 5% GST tax across all prices simultaneously
prices_with_tax = base_prices * 1.05

print("Base Prices:", base_prices)
print("Prices with 5% GST:", prices_with_tax)
Output: Base Prices: [100 200 300 400] Prices with 5% GST: [105. 210. 315. 420. ]
Real-Time Example 3: Array Slicing & Indexing
Extract specific rows, columns, or sub-grids from multi-dimensional NumPy matrices.
Python
import numpy as np

matrix = np.array([
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90]
])

print("Element at row 0, col 2:", matrix[0, 2])
print("Entire second row:", matrix[1, :])
print("Entire third column:", matrix[:, 2])
Output: Element at row 0, col 2: 30 Entire second row: [40 50 60] Entire third column: [30 60 90]
Real-Time Example 4: Reshaping Arrays (.reshape())
Transform flat 1D arrays into structured multi-dimensional 2D or 3D grids using .reshape().
Python
import numpy as np

# Create a flat array of 12 numbers
flat_arr = np.arange(1, 13)

# Reshape into a 3 x 4 matrix
grid_3_4 = flat_arr.reshape(3, 4)

print("Original Flat Array:", flat_arr)
print("\nReshaped 3x4 Grid:\n", grid_3_4)
Output: Original Flat Array: [ 1 2 3 4 5 6 7 8 9 10 11 12] Reshaped 3x4 Grid: [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
Real-Time Example 5: Statistical Aggregation (mean, sum, std)
Calculate statistical metrics across datasets instantly using built-in NumPy aggregation functions.
Python
import numpy as np

student_scores = np.array([85, 92, 78, 90, 88, 95])

print("Total Sum of Scores:", np.sum(student_scores))
print("Average Score (Mean):", np.mean(student_scores))
print("Highest Score (Max):", np.max(student_scores))
print("Standard Deviation:", round(np.std(student_scores), 2))
Output: Total Sum of Scores: 538 Average Score (Mean): 89.66666666666667 Highest Score (Max): 95 Standard Deviation: 5.42
Real-Time Example 6: Conditional Filtering & Boolean Masking
Filter datasets dynamically by passing boolean condition masks directly into array brackets.
Python
import numpy as np

product_prices = np.array([450, 1200, 300, 2500, 850, 1500])

# Filter products priced strictly greater than ₹1000
expensive_products = product_prices[product_prices > 1000]

print("Original Prices:", product_prices)
print("Filtered Expensive Prices (> ₹1000):", expensive_products)
Output: Original Prices: [ 450 1200 300 2500 850 1500] Filtered Expensive Prices (> ₹1000): [1200 2500 1500]
Real-Time Example 7: Matrix Multiplication (Dot Product)
Compute matrix dot products efficiently using np.dot() or the @ operator.
Python
import numpy as np

matrix_a = np.array([
    [1, 2],
    [3, 4]
])

matrix_b = np.array([
    [5, 6],
    [7, 8]
])

# Matrix multiplication using @ operator
result_dot = matrix_a @ matrix_b

print("Matrix Dot Product Result:\n", result_dot)
Output: Matrix Dot Product Result: [[19 22] [43 50]]
Real-Time Example 8: Broadcasting
Perform arithmetic operations between arrays of different shapes seamlessly using NumPy broadcasting rules.
Python
import numpy as np

matrix = np.array([
    [10, 20, 30],
    [40, 50, 60]
])

# Adding a 1D vector [1, 2, 3] to every row of a 2D matrix via broadcasting
vector_bias = np.array([1, 2, 3])

broadcasted_result = matrix + vector_bias

print("Broadcasted Matrix Addition Result:\n", broadcasted_result)
Output: Broadcasted Matrix Addition Result: [[11 22 33] [41 52 63]]
Real-Time Example 9: Random Number Generation (np.random)
Generate synthetic random datasets and normal distributions for machine learning tests and simulations.
Python
import numpy as np

# Set seed for reproducibility
np.random.seed(42)

# Generate 5 random integers between 1 and 100
random_ints = np.random.randint(1, 100, 5)

# Generate 3 random samples from a normal distribution
normal_samples = np.random.randn(3)

print("Random Integers:", random_ints)
print("Normal Distribution Samples:", normal_samples)
Output: Random Integers: [52 92 15 72 61] Normal Distribution Samples: [ 0.49671415 -0.1382643 0.64768854]