NumPy - The Array Processing Powerhouse

Introduction

NumPy (Numerical Python) is the ultimate math wizard in the Python world! It’s like a turbocharged calculator that handles large arrays and matrices efficiently. If Python lists are bicycles, then NumPy arrays are rocket-powered race cars!

Installing NumPy

Before we unleash the power of NumPy, let’s install it:

pip install numpy

Check if it’s installed correctly:

import numpy as np
print(np.__version__)

Creating NumPy Arrays

Converting a Python list into a NumPy array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

Boom! Now you have a NumPy array!

Creating a matrix (2D array):

matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)

Array Operations 

NumPy arrays support element-wise operations, making them much faster than Python lists.

arr = np.array([1, 2, 3, 4])
print(arr * 2)  # [2 4 6 8]
print(arr + 5)  # [6 7 8 9]
print(arr ** 2) # [1 4 9 16]

No need for loops—NumPy does the magic automatically!

Useful NumPy Functions

Function Description
np.zeros((3,3)) Creates a 3×3 matrix of zeros
np.ones((2,2)) Creates a 2×2 matrix of ones
np.arange(0,10,2) Creates an array [0, 2, 4, 6, 8]
np.linspace(0,1,5) Generates 5 evenly spaced numbers between 0 and 1
np.random.rand(3,3) Creates a 3×3 matrix of random numbers

Example:

rand_matrix = np.random.rand(3,3)
print(rand_matrix)

Indexing & Slicing

NumPy makes it easy to grab specific elements from an array.

arr = np.array([10, 20, 30, 40, 50])
print(arr[1])    # 20 (Indexing)
print(arr[1:4])  # [20 30 40] (Slicing)
print(arr[-1])   # 50 (Negative Indexing)

For 2D arrays:

matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix[1, 2])  # 6 (Row 1, Column 2)
print(matrix[:, 1])  # [2 5] (Second column)

Reshaping & Transposing

Reshaping an array:

arr = np.array([1, 2, 3, 4, 5, 6])
reshaped = arr.reshape(2, 3)
print(reshaped)

Transposing a matrix:

matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.T)

Summary 

Feature NumPy Advantage
Arrays Faster than Python lists
Math Operations Element-wise calculations
Indexing Powerful slicing and dicing
Reshaping Easily modify array shapes
Random Numbers Generate matrices with random values

NumPy is the backbone of numerical computing in Python. Now you’re ready to conquer arrays like a pro! 

Post a Comment

0 Comments