0% found this document useful (0 votes)
12 views20 pages

Numpy Cheat Sheet

This document is a comprehensive cheat sheet for the NumPy library, detailing array creation methods, attributes, and indexing techniques. It includes examples for each method and concept, making it a valuable resource for both beginners and advanced users. The cheat sheet covers essential functionalities such as creating arrays, accessing their properties, and manipulating data within arrays.

Uploaded by

Bharat Konduru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views20 pages

Numpy Cheat Sheet

This document is a comprehensive cheat sheet for the NumPy library, detailing array creation methods, attributes, and indexing techniques. It includes examples for each method and concept, making it a valuable resource for both beginners and advanced users. The cheat sheet covers essential functionalities such as creating arrays, accessing their properties, and manipulating data within arrays.

Uploaded by

Bharat Konduru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

‭ ot it!

Here's a comprehensive cheat sheet for the NumPy library, covering everything from‬
G
‭basic array creation to advanced operations, complete with examples for each method and‬
‭concept.‬

‭ umPy Library: The Ultimate Cheat Sheet (Basic to‬


N
‭Advanced)‬
‭ umPy (Numerical Python) is the fundamental package for numerical computation in Python.‬
N
‭It provides powerful N-dimensional array objects and tools for integrating C/C++/Fortran‬
‭code. It's the backbone of many scientific computing libraries in Python (e.g., SciPy,‬
‭scikit-learn, Matplotlib).‬

‭How to get started:‬

‭ irst, ensure you have NumPy installed:‬


F
‭pip install numpy‬
‭Then, import it into your Python script or interactive session:‬

‭Python‬

‭import‬‭numpy‬‭as‬‭np‬

‭I. Array Creation‬


‭The core of NumPy is the ndarray object. Here's how to create them.‬

‭Method/Concept‬ ‭Description‬ ‭Example‬ ‭ utput‬


O
‭(simplified)‬

‭np.array(list)‬ ‭ reates an array‬


C ‭np.array([1, 2, 3])‬ ‭[1 2 3]‬
‭from a Python list‬
‭or tuple.‬

‭ p.array([[1, 2], [3,‬


n ‭[[1 2]\n [3 4]]‬
‭4]])‬
‭np.zeros(shape)‬ ‭ reates an array‬
C ‭np.zeros(3)‬ ‭[0. 0. 0.]‬
‭filled with zeros.‬
‭shape is a tuple.‬

‭np.zeros((2, 3))‬ [‭ [0. 0. 0.]\n [0. 0.‬


‭0.]]‬

‭np.ones(shape)‬ ‭ reates an array‬


C ‭np.ones((2, 2))‬ ‭[[1. 1.]\n [1. 1.]]‬
‭filled with ones.‬

‭np.empty(shape)‬ ‭ reates an array‬


C ‭np.empty((2, 2))‬ [‭ [... ...]\n [... ...]]‬
‭without initializing‬ ‭(values vary)‬
‭entries (may‬
‭contain garbage‬
‭values, faster than‬
‭zeros/ones).‬

‭ p.arange(start,‬
n ‭ reates an array‬
C ‭np.arange(0, 10, 2)‬ ‭[0 2 4 6 8]‬
‭stop, step)‬ ‭with regularly‬
‭spaced values (like‬
‭Python's range()).‬
‭stop is exclusive.‬

‭ p.linspace(start,‬
n ‭ reates an array‬
C ‭np.linspace(0, 1, 5)‬ [‭ 0. 0.25 0.5 0.75 1.‬
‭stop, num)‬ ‭with num evenly‬ ‭]‬
‭spaced values over‬
‭a specified interval.‬
‭stop is inclusive by‬
‭default.‬

‭np.eye(N)‬ ‭ reates an identity‬


C ‭np.eye(3)‬ [‭ [1. 0. 0.]\n [0. 1.‬
‭matrix of size N x N.‬ ‭0.]\n [0. 0. 1.]]‬

‭np.diag(v)‬ ‭ reates a 2D array‬


C ‭np.diag([1, 2, 3])‬ [‭ [1 0 0]\n [0 2 0]\n‬
‭with v on the‬ ‭[0 0 3]]‬
‭diagonal and zeros‬
‭elsewhere, or‬
‭extracts a diagonal.‬
‭ p.full(shape,‬
n ‭ reates an array of‬
C ‭np.full((2, 2), 7)‬ ‭[[7 7]\n [7 7]]‬
‭fill_value)‬ ‭a given shape filled‬
‭with fill_value.‬

‭ p.random.rand(d0‬
n ‭ reates an array of‬
C ‭ p.random.rand(2,‬
n [‭ [0.12 0.87]\n [0.34‬
‭, d1, ...)‬ ‭the given shape,‬ ‭2)‬ ‭0.56]] (random)‬
‭filled with random‬
‭samples from a‬
‭uniform distribution‬
‭over [0, 1).‬

‭ p.random.randn(d‬
n ‭ reates an array of‬
C ‭ p.random.randn(2,‬
n [‭ [-0.5 1.2]\n [ 0.1‬
‭0, d1, ...)‬ ‭the given shape,‬ ‭2)‬ ‭-0.8]] (random)‬
‭filled with random‬
‭samples from a‬
‭standard normal‬
‭distribution (mean‬
‭0, variance 1).‬

‭ p.random.randint(l‬
n ‭ reates an array of‬
C ‭ p.random.randint(‬
n ‭[2 8 1 5 9] (random)‬
‭ow, high, size)‬ ‭random integers‬ ‭0, 10, 5)‬
‭from low (inclusive)‬
‭to high (exclusive).‬

‭Example Usage:‬

‭Python‬

‭import‬‭numpy‬‭as‬‭np‬

‭ rint(‬‭"--- Array Creation ---"‬‭)‬


p
‭arr1d = np.array([‬‭1‬‭,‬‭2‭,‬‬‭3‭]‬ )‬
‭print(‬‭f"1D Array:‬‭{arr1d}‬‭"‬‭)‬

‭ rr2d = np.array([[‬‭1‭,‬‬‭2‭]‬ , [‬‭3‭,‬‬‭4‬‭]])‬


a
‭print(‬‭f"2D Array:\n‬‭{arr2d}‬‭"‭)‬ ‬

‭zeros_arr = np.zeros((‬‭2‭,‬‬‭4‭)‬ )‬
‭print(‬‭f"Zeros Array (2x4):\n‬‭{zeros_arr}‬‭"‭)‬ ‬

‭ nes_arr = np.ones(‬‭3‭)‬ ‬
o
‭print(‬‭f"Ones Array (1x3):‬‭{ones_arr}‬‭"‬‭)‬

‭ range_arr = np.arange(‬‭5‭,‬‬‭15‬‭,‬‭3‬‭)‬
a
‭print(‬‭f"Arange Array (5 to 15 step 3):‬‭{arange_arr}‬‭"‬‭)‬

l‭inspace_arr = np.linspace(‬‭0‭,‬‬‭10‬‭,‬‭5‬‭)‬‭# 5 points from‬‭0 to 10, inclusive‬


‭print(‬‭f"Linspace Array (0 to 10, 5 points):‬‭{linspace_arr}‬‭"‬‭)‬

i‭dentity_matrix = np.eye(‬‭4‬‭)‬
‭print(‬‭f"Identity Matrix (4x4):\n‬‭{identity_matrix}‬‭"‬‭)‬

f‭ ull_arr = np.full((‬‭3‭,‬‬‭3‭)‬ ,‬‭99‬‭)‬


‭print(‬‭f"Full Array (3x3 with 99):\n‬‭{full_arr}‬‭"‬‭)‬

r‭ and_arr = np.random.rand(‬‭2‭,‬‬‭2‭)‬ ‬
‭print(‬‭f"Random Uniform (2x2):\n‬‭{rand_arr}‬‭"‭)‬ ‬

r‭ andn_arr = np.random.randn(‬‭1‭,‬‬‭3‭)‬ ‬
‭print(‬‭f"Random Normal (1x3):\n‬‭{randn_arr}‬‭"‬‭)‬

r‭ andint_arr = np.random.randint(‬‭1‭,‬‬‭10‬‭, size=(‬‭2‭,‬‭3‬ ‬‭))‬


‭print(‬‭f"Random Integers (2x3, 1-9):\n‬‭{randint_arr}‬‭"‬‭)‬

‭II. Array Attributes‬


‭Properties that describe the structure and content of an array.‬

‭Attribute‬ ‭Description‬ ‭Example‬ ‭Output‬

‭arr.ndim‬ ‭ umber of‬


N ‭arr2d.ndim‬ ‭2‬
‭dimensions (axes).‬

‭arr.shape‬ ‭ uple of array‬


T ‭arr2d.shape‬ ‭(2, 2)‬
‭dimensions.‬

‭arr.size‬ ‭ otal number of‬


T ‭arr2d.size‬ ‭4‬
‭elements in the‬
‭array.‬

‭arr.dtype‬ ‭ ata type of the‬


D ‭arr2d.dtype‬ ‭ type('int64') (or‬
d
‭elements in the‬ ‭int32 etc.)‬
‭array.‬

‭arr.itemsize‬ ‭ ize in bytes of‬


S ‭arr2d.itemsize‬ ‭8 (for int64)‬
‭each element.‬

‭arr.nbytes‬ ‭ otal bytes‬


T ‭arr2d.nbytes‬ ‭ 2 (for 4 elements,‬
3
‭consumed by the‬ ‭8 bytes each)‬
‭array data.‬

‭arr.T‬ ‭ he transposed‬
T ‭arr2d.T‬ ‭[[1 3]\n [2 4]]‬
‭array.‬

‭Example Usage:‬

‭Python‬

‭import‬‭numpy‬‭as‬‭np‬

‭ rint(‬‭"\n--- Array Attributes ---"‬‭)‬


p
‭arr = np.array([[‬‭1‭,‬‬‭2‭,‬‬‭3‭]‬ , [‬‭4‬‭,‬‭5‭,‬‬‭6‬‭]], dtype=np.float32)‬

‭ rint(‬‭f"Array:\n‬‭{arr}‬‭"‭)‬ ‬
p
‭print(‬‭f"Dimensions (ndim):‬‭{arr.ndim}‬‭"‭)‬ ‬
‭print(‬‭f"Shape:‬‭{arr.shape}‬‭"‬‭)‬
‭print(‬‭f"Total elements (size):‬‭{arr.size}‬‭"‬‭)‬
‭print(‬‭f"Data type (dtype):‬‭{arr.dtype}‬‭"‬‭)‬
‭print(‬‭f"Item size (bytes):‬‭{arr.itemsize}‬‭"‬‭)‬
‭print(‬‭f"Total bytes (nbytes):‬‭{arr.nbytes}‬‭"‬‭)‬
‭print(‬‭f"Transposed array (arr.T):\n‬‭{arr.T}‬‭"‭)‬ ‬

‭III. Indexing and Slicing‬


‭Accessing and manipulating subsets of arrays.‬

‭Concept‬ ‭Description‬ ‭Example‬ ‭Output‬

‭Basic Indexing‬ ‭ ccess a single‬


A ‭ rr = np.array([10,‬
a ‭20‬
‭element.‬ ‭20, 30]) <br> arr[1]‬

‭ rr2d =‬
a ‭2‬
‭np.array([[1,2],[3,4]‬
‭]) <br> arr2d[0, 1]‬

‭Slicing (1D)‬ ‭arr[start:end:step]‬ ‭arr[1:4]‬ ‭[20 30 40]‬

‭Slicing (2D)‬ ‭ rr[row_start:row_e‬


a ‭arr2d[0:2, 0]‬ ‭[1 3] (first column)‬
‭nd,‬
‭col_start:col_end]‬

‭arr2d[:, 1]‬ [‭ 2 4] (second‬


‭column)‬

‭arr2d[0, :]‬ ‭[1 2] (first row)‬

‭Boolean Indexing‬ ‭ elect elements‬


S ‭ rr = np.array([1, 5,‬
a ‭[5 8]‬
‭based on a boolean‬ ‭2, 8]) <br> arr[arr >‬
‭condition.‬ ‭3]‬

‭Fancy Indexing‬ ‭ elect elements‬


S ‭ rr = np.array([10,‬
a ‭[10 30]‬
‭using an array of‬ ‭20, 30, 40]) <br>‬
‭indices.‬ ‭arr[[0, 2]]‬

‭arr2d[[0,1], [1,0]]‬ [‭ 2 3] (elements at‬


‭(0,1) and (1,0))‬

‭Example Usage:‬

‭Python‬
‭import‬‭numpy‬‭as‬‭np‬

‭ rint(‬‭"\n--- Indexing and Slicing ---"‬‭)‬


p
‭arr_1d = np.arange(‬‭10‬‭,‬‭60‬‭,‬‭10‬‭)‬‭# [10 20 30 40 50]‬
‭print(‬‭f"1D Array:‬‭{arr_1d}‬‭"‬‭)‬
‭print(‬‭f"Element at index 2:‬‭{arr_1d[‬‭2‭]‬ }‬‭"‬‭)‬‭# 30‬
‭print(‬‭f"Elements from index 1 to 3 (exclusive):‬‭{arr_1d[‬‭1‬‭:‬‭4‭]‬ }‬‭"‬‭)‬‭# [20 30 40]‬
‭print(‬‭f"Every second element:‬‭{arr_1d[::‬‭2‬‭]}‬‭"‭)‬ ‬‭# [10‬‭30 50]‬

‭arr_2d = np.array([[‬‭1‬‭,‬‭2‭,‬‬‭3‭]‬ ,‬
‭[‬‭4‭,‬‬‭5‭,‬‬‭6‬‭],‬
‭[‬‭7‭,‬‬‭8‭,‬‬‭9‬‭]])‬
‭print(‬‭f"\n2D Array:\n‬‭{arr_2d}‬‭"‬‭)‬
‭print(‬‭f"Element at (1, 2):‬‭{arr_2d[‬‭1‬‭,‬‭2‭]‬ }‬‭"‬‭)‬‭# 6‬
‭print(‬‭f"First row:‬‭{arr_2d[‬‭0‭,‬ :]}‬‭"‬‭)‬‭# [1 2 3]‬
‭print(‬‭f"Second column:‬‭{arr_2d[:,‬‭1‭]‬ }‬‭"‬‭)‬‭# [2 5 8]‬
‭print(‬‭f"Sub-array (first 2 rows, last 2 cols):\n‬‭{arr_2d[‬‭0‬‭:‭2‬ ‬‭,‬‭1‭:‬‬‭3‭]‬ }‬‭"‬‭)‬‭# [[2 3]\n [5 6]]‬

‭# Boolean Indexing‬
‭print(‬‭f"\nBoolean Indexing (elements > 5):‬‭{arr_2d[arr_2d‬‭>‬‭5‬‭]}‬‭"‭)‬ ‬‭# [6 7 8 9]‬

‭# Fancy Indexing‬
r‭ ow_indices = np.array([‬‭0‬‭,‬‭2‬‭])‬
‭col_indices = np.array([‬‭0‭,‬‬‭1‭]‬ )‬
‭print(‬‭f"Fancy Indexing (rows 0, 2 and cols 0, 1):\n‬‭{arr_2d[row_indices[:,‬‭np.newaxis], col_indices]}‬‭"‬‭)‬
‭ [[1 2]‬
#
‭# [7 8]]‬
‭print(‬‭f"Fancy Indexing (elements at (0,0) and (2,1)):‬‭{arr_2d[[‬‭0‭,‬‬‭2‭]‬ , [‬‭0‬‭,‬‭1‭]‬ ]}‬‭"‬‭)‬‭# [1 8]‬

‭IV. Array Manipulation‬


‭Changing the shape, size, or order of elements in arrays.‬

‭Method‬ ‭Description‬ ‭Example‬ ‭Output‬

‭ rr.reshape(new_sh‬
a ‭ ives a new shape‬
G ‭ rr = np.arange(6)‬
a ‭[[0 1 2]\n [3 4 5]]‬
‭ape)‬ ‭to an array without‬ ‭<br> arr.reshape(2,‬
‭changing its data.‬ ‭3)‬
‭arr.flatten()‬ ‭ eturns a copy of‬
R ‭arr2d.flatten()‬ ‭[1 2 3 4]‬
‭the array collapsed‬
‭into one dimension.‬

‭arr.ravel()‬ ‭ eturns a flattened‬


R ‭arr2d.ravel()‬ ‭[1 2 3 4]‬
‭view of the array‬
‭(changes to view‬
‭affect original).‬

‭arr.T‬ ‭ ransposes the‬


T ‭arr2d.T‬ ‭[[1 3]\n [2 4]]‬
‭array (swaps rows‬
‭and columns).‬

‭ p.concatenate((ar‬
n ‭ oins a sequence‬
J ‭ =np.ones(2) <br>‬
a ‭[1. 1. 0. 0.]‬
‭r1, arr2), axis=0/1)‬ ‭of arrays along an‬ ‭b=np.zeros(2) <br>‬
‭existing axis.‬ ‭np.concatenate((a,‬
‭b))‬

‭ p.concatenate((ar‬
n ‭[[1 2 1 2]\n [3 4 3 4]]‬
‭r2d, arr2d), axis=1)‬

‭ p.vstack((arr1,‬
n ‭ tacks arrays‬
S ‭ =np.array([1,2])‬
a ‭[[1 2]\n [3 4]]‬
‭arr2))‬ ‭vertically‬ ‭<br>‬
‭(row-wise).‬ ‭b=np.array([3,4])‬
‭<br>‬
‭np.vstack((a,b))‬

‭ p.hstack((arr1,‬
n ‭ tacks arrays‬
S ‭np.hstack((a,b))‬ ‭[1 2 3 4]‬
‭arr2))‬ ‭horizontally‬
‭(column-wise).‬

‭ p.split(arr,‬
n ‭ plits an array into‬
S ‭np.split(arr_1d, 2)‬ [‭ array([10, 20, 30]),‬
‭indices_or_sections‬ ‭multiple‬ ‭array([40, 50])]‬
‭, axis=0/1)‬ ‭sub-arrays.‬

‭ p.append(arr,‬
n ‭ ppends values to‬
A ‭ p.append(arr1d,‬
n [‭ 10 20 30 40 50‬
‭values, axis=None)‬ ‭the end of an array.‬ ‭60)‬ ‭60]‬
‭Returns a new‬
‭array.‬
‭ p.delete(arr, obj,‬
n ‭ eturns a new array‬
R ‭np.delete(arr1d, 0)‬ ‭[20 30 40 50]‬
‭axis=None)‬ ‭with sub-arrays‬
‭along an axis‬
‭deleted.‬

‭ p.insert(arr, obj,‬
n I‭nserts values along‬ ‭ p.insert(arr1d, 1,‬
n ‭[10 15 20 30 40 50]‬
‭values, axis=None)‬ ‭the given axis‬ ‭15)‬
‭before the given‬
‭indices.‬

‭arr.copy()‬ ‭ reates a deep‬


C ‭b = arr.copy()‬
‭copy of the array‬
‭(changes to copy‬
‭don't affect‬
‭original).‬

‭ rr.astype(new_dty‬
a ‭ onverts the array‬
C ‭arr.astype(float)‬ [‭ [1. 2. 3.]] (if arr was‬
‭pe)‬ ‭to a specified data‬ ‭int)‬
‭type.‬

‭Example Usage:‬

‭Python‬

‭import‬‭numpy‬‭as‬‭np‬

‭ rint(‬‭"\n--- Array Manipulation ---"‬‭)‬


p
‭arr_original = np.arange(‬‭12‬‭)‬
‭print(‬‭f"Original 1D Array:‬‭{arr_original}‬‭"‬‭)‬

‭# Reshape‬
r‭ eshaped_arr = arr_original.reshape(‬‭3‬‭,‬‭4‭)‬ ‬
‭print(‬‭f"Reshaped to (3, 4):\n‬‭{reshaped_arr}‬‭"‭)‬ ‬

‭# Flatten‬
‭ at_arr = reshaped_arr.flatten()‬
fl
‭print(‬‭f"Flattened:‬‭{flat_arr}‬‭"‭)‬ ‬
‭# Ravel (view)‬
r‭ aveled_arr = reshaped_arr.ravel()‬
‭raveled_arr[‬‭0‭]‬ =‬‭99‬‭# Changes original as well‬
‭print(‬‭f"Raveled (first element changed to 99):‬‭{raveled_arr}‬‭"‬‭)‬
‭print(‬‭f"Original array after ravel change:\n‬‭{reshaped_arr}‬‭"‬‭)‬

‭# Transpose‬
‭print(‬‭f"Transposed:\n‬‭{reshaped_arr.T}‬‭"‭)‬ ‬

‭# Concatenate‬
‭ rr_a = np.array([[‬‭1‭,‬‬‭2‭]‬ , [‬‭3‭,‬‬‭4‬‭]])‬
a
‭arr_b = np.array([[‬‭5‬‭,‬‭6‬‭], [‬‭7‭,‬‬‭8‬‭]])‬
‭concat_rows = np.concatenate((arr_a, arr_b), axis=‬‭0‬‭)‬
‭print(‬‭f"\nConcatenate (axis=0):\n‬‭{concat_rows}‬‭"‬‭)‬
‭concat_cols = np.concatenate((arr_a, arr_b), axis=‬‭1‭)‬ ‬
‭print(‬‭f"Concatenate (axis=1):\n‬‭{concat_cols}‬‭"‭)‬ ‬

‭# Vstack / Hstack‬
v‭ _stack = np.vstack((arr_a, arr_b))‬
‭print(‬‭f"Vstack:\n‬‭{v_stack}‬‭"‭)‬ ‬
‭h_stack = np.hstack((arr_a, arr_b))‬
‭print(‬‭f"Hstack:\n‬‭{h_stack}‬‭"‬‭)‬

‭# Split‬
‭ rr_to_split = np.arange(‬‭9‬‭)‬
a
‭split_arr = np.split(arr_to_split,‬‭3‬‭)‬‭# Split into‬‭3 equal parts‬
‭print(‬‭f"Split array:‬‭{split_arr}‬‭"‬‭)‬

‭# Append, Delete, Insert‬


‭ ew_arr = np.append(arr_original, [‬‭100‬‭,‬‭101‬‭])‬
n
‭print(‬‭f"Appended:‬‭{new_arr}‬‭"‬‭)‬
‭deleted_arr = np.delete(new_arr, [‬‭0‭,‬‬‭1‬‭])‬‭# Delete‬‭elements at index 0 and 1‬
‭print(‬‭f"Deleted elements at 0, 1:‬‭{deleted_arr}‬‭"‭)‬ ‬
‭inserted_arr = np.insert(deleted_arr,‬‭2‭,‬ [‬‭500‬‭,‬‭600‬‭])‬‭# Insert at index 2‬
‭print(‬‭f"Inserted at index 2:‬‭{inserted_arr}‬‭"‬‭)‬

‭# Copy‬
‭ rr_copy = arr_original.copy()‬
a
‭arr_original[‬‭0‭]‬ =‬‭0‬‭# Modify original‬
‭arr_copy[‬‭0‬‭] =‬‭999‬ ‭# Modify copy‬
‭print(‬‭f"Original (after copy modification):‬‭{arr_original}‬‭"‬‭)‬
‭print(‬‭f"Copy (after its own modification):‬‭{arr_copy}‬‭"‭)‬ ‬

‭# Astype‬
‭ oat_arr = arr_original.astype(np.float32)‬
fl
‭print(‬‭f"Converted to float:‬‭{float_arr.dtype}‬‭"‭)‬ ‬

‭V. Mathematical Operations‬


‭Element-wise operations, aggregations, and linear algebra.‬

‭A. Element-wise Operations‬


‭ umPy arrays support element-wise operations with scalars and other arrays (broadcasting‬
N
‭rules apply).‬

‭Operation‬ ‭Description‬ ‭Example‬ ‭Output‬

‭arr + scalar‬ ‭Addition‬ ‭ = np.array([1, 2])‬


a ‭[11 12]‬
‭<br> a + 10‬

‭arr * arr‬ ‭ lement-wise‬


E ‭a * a‬ ‭[1 4]‬
‭multiplication‬

‭np.add(arr1, arr2)‬ ‭ lement-wise‬


E ‭np.add(a, [3, 4])‬ ‭[4 6]‬
‭addition.‬

‭ p.subtract(arr1,‬
n ‭ lement-wise‬
E ‭ p.subtract(a, [3,‬
n ‭[-2 -2]‬
‭arr2)‬ ‭subtraction.‬ ‭4])‬

‭ p.multiply(arr1,‬
n ‭ lement-wise‬
E ‭ p.multiply(a, [3,‬
n ‭[3 8]‬
‭arr2)‬ ‭multiplication.‬ ‭4])‬

‭np.divide(arr1, arr2)‬ ‭ lement-wise‬


E ‭np.divide(a, [2, 1])‬ ‭[0.5 2. ]‬
‭division.‬

‭np.sqrt(arr)‬ ‭ lement-wise‬
E ‭np.sqrt([4, 9])‬ ‭[2. 3.]‬
‭square root.‬

‭np.exp(arr)‬ ‭ lement-wise‬
E ‭np.exp([0, 1])‬ ‭[1. 2.71828183]‬
‭exponential (ex).‬

‭np.log(arr)‬ ‭Element-wise‬ ‭np.log([1, math.e])‬ ‭[0. 1.]‬


‭natural logarithm.‬

‭ p.sin(arr),‬
n ‭ lement-wise‬
E ‭ p.sin([0,‬
n ‭[0. 1.]‬
‭np.cos(arr),‬ ‭trigonometric‬ ‭math.pi/2])‬
‭np.tan(arr)‬ ‭functions (radians).‬

‭B. Aggregate Functions‬


‭Summarize array data (e.g., sum, mean, min, max). Can specify axis.‬

‭Method‬ ‭Description‬ ‭Example‬ ‭Output‬

‭arr.sum(axis=None)‬ ‭ um of all elements‬


S ‭ rr =‬
a ‭10‬
‭or along a specified‬ ‭np.array([[1,2],[3,4]‬
‭axis.‬ ‭]) <br> arr.sum()‬

‭arr.sum(axis=0)‬ ‭[4 6] (column sums)‬

‭arr.sum(axis=1)‬ ‭[3 7] (row sums)‬

‭ rr.mean(axis=Non‬
a ‭ ean of all‬
M ‭arr.mean()‬ ‭2.5‬
‭e)‬ ‭elements or along‬
‭an axis.‬

‭arr.min(axis=None)‬ ‭Minimum element.‬ ‭arr.min()‬ ‭1‬

‭arr.max(axis=None)‬ ‭Maximum element.‬ ‭arr.max()‬ ‭4‬

‭ rr.argmin(axis=No‬
a I‭ndex of minimum‬ ‭arr.argmin()‬ ‭0 (flattened index)‬
‭ne)‬ ‭element.‬

‭ rr.argmax(axis=No‬
a I‭ndex of maximum‬ ‭arr.argmax(axis=1)‬ [‭ 1 1] (index of max‬
‭ne)‬ ‭element.‬ ‭in each row)‬

‭arr.std(axis=None)‬ ‭Standard deviation.‬ ‭arr.std()‬ ‭1.118...‬

‭arr.var(axis=None)‬ ‭Variance.‬ ‭arr.var()‬ ‭1.25‬


‭ p.median(arr,‬
n ‭ edian of‬
M ‭np.median(arr)‬ ‭2.5‬
‭axis=None)‬ ‭elements.‬

‭C. Linear Algebra‬


‭Essential for scientific and data applications.‬

‭Method‬ ‭Description‬ ‭Example‬ ‭Output‬

‭arr1 @ arr2‬ ‭ atrix‬


M ‭ =np.array([[1,2],[3,‬
A ‭[[19 22]\n [43 50]]‬
‭multiplication‬ ‭4]]) <br>‬
‭(Python 3.5+).‬ ‭B=np.array([[5,6],[7‬
‭,8]]) <br> A @ B‬

‭np.dot(arr1, arr2)‬ ‭ ot product for 1D‬


D ‭np.dot(A, B)‬ ‭[[19 22]\n [43 50]]‬
‭arrays, matrix‬
‭multiplication for‬
‭2D.‬

‭np.linalg.det(arr)‬ ‭ omputes the‬


C ‭ p.linalg.det(np.eye‬
n ‭1.0‬
‭determinant of a‬ ‭(2))‬
‭square matrix.‬

‭np.linalg.inv(arr)‬ ‭ omputes the‬


C ‭ p.linalg.inv(np.arra‬
n [‭ [-2. 1. ]\n [ 1.5‬
‭inverse of a square‬ ‭y([[1,2],[3,4]]))‬ ‭-0.5]]‬
‭matrix.‬

‭np.linalg.eig(arr)‬ ‭ omputes the‬


C ‭ p.linalg.eig(np.arra‬
n (‭ eigenvalues,‬
‭eigenvalues and‬ ‭y([[1,2],[3,4]]))‬ ‭eigenvectors)‬
‭right eigenvectors‬
‭of a square matrix.‬

‭np.linalg.solve(A, b)‬ ‭ olves a linear‬


S ‭ = np.array([[2, 1],‬
A [‭ 1. 1.] (solution for x‬
‭system of‬ ‭[1, 1]]) <br> b =‬ ‭and y)‬
‭equations Ax = b.‬ ‭np.array([3, 2]) <br>‬
‭np.linalg.solve(A, b)‬

‭Example Usage:‬
‭Python‬

‭import‬‭numpy‬‭as‬‭np‬
‭import‬‭math‬

‭ rint(‬‭"\n--- Mathematical Operations ---"‬‭)‬


p
‭arr_math = np.array([[‬‭1‭,‬‬‭2‭,‬‬‭3‭]‬ ,‬
‭[‭4
‬ ‬‭,‬‭5‬‭,‬‭6‬‭]])‬

‭# Element-wise operations‬
‭print(‬‭f"Array + 10:‬‭{arr_math +‬‭10‬‭}‭"‬ ‬‭)‬
‭ rint(‬‭f"Array * 2:‬‭{arr_math *‬‭2‬‭}‭"‬ ‬‭)‬
p
‭print(‬‭f"Square root of arr_math:\n‬‭{np.sqrt(arr_math)}‬‭"‬‭)‬

‭# Aggregate Functions‬
‭print(‬‭f"\nSum of all elements:‬‭{arr_math.‬‭sum‬‭()}‬‭"‭)‬ ‬
‭ rint(‬‭f"Sum along axis 0 (columns):‬‭{arr_math.‬‭sum‬‭(axis=‬‭0‭)‬ }‬‭"‬‭)‬‭# [1+4, 2+5, 3+6] = [5 7 9]‬
p
‭print(‬‭f"Mean of all elements:‬‭{arr_math.mean()}‬‭"‭)‬ ‬
‭print(‬‭f"Min element:‬‭{arr_math.‬‭min‬‭()}‬‭"‭)‬ ‬
‭print(‬‭f"Max element along axis 1 (rows):‬‭{arr_math.‬‭max‬‭(axis=‬‭1‬‭)}‬‭"‬‭)‬‭# [max(1,2,3), max(4,5,6)] = [3 6]‬
‭print(‬‭f"Standard Deviation:‬‭{arr_math.std()}‬‭"‭)‬ ‬
‭print(‬‭f"Median:‬‭{np.median(arr_math)}‬‭"‬‭)‬

‭# Linear Algebra‬
‭ atrix_A = np.array([[‬‭1‬‭,‬‭2‬‭], [‬‭3‬‭,‬‭4‭]‬ ])‬
m
‭matrix_B = np.array([[‬‭5‭,‬‬‭6‬‭], [‬‭7‬‭,‬‭8‭]‬ ])‬

‭ rint(‬‭f"\nMatrix A:\n‬‭{matrix_A}‬‭"‬‭)‬
p
‭print(‬‭f"Matrix B:\n‬‭{matrix_B}‬‭"‬‭)‬
‭print(‬‭f"Matrix Multiplication (A @ B):\n‬‭{matrix_A‬‭@ matrix_B}‬‭"‭)‬ ‬
‭print(‬‭f"Determinant of A:‬‭{np.linalg.det(matrix_A)}‬‭"‭)‬ ‬
‭print(‬‭f"Inverse of A:\n‬‭{np.linalg.inv(matrix_A)}‬‭"‭)‬ ‬

‭# Solving linear equations: 2x + y = 5, x + 3y = 10‬


‭C = np.array([[‬‭2‭,‬‬‭1‭]‬ , [‬‭1‬‭,‬‭3‭]‬ ])‬
‭ = np.array([‬‭5‬‭,‬‭10‬‭])‬
d
‭solution = np.linalg.solve(C, d)‬
‭print(‬‭f"Solution for linear system (Cx = d):‬‭{solution}‬‭"‬‭)‬‭# Should be [1. 3.]‬
‭VI. Broadcasting‬
‭ umPy's powerful mechanism for performing operations on arrays of different shapes. It‬
N
‭implicitly "stretches" the smaller array to match the larger one without actually duplicating‬
‭data.‬

‭Rules for Broadcasting:‬


‭1.‬ E ‭ qual ndim (dimensions):‬‭If arrays don't have the‬‭same number of dimensions, prepend‬
‭1s to the smaller array's shape until‬‭ndim‬‭matches.‬
‭2.‬ ‭Compatibility:‬‭Two dimensions are compatible when:‬
‭○‬ ‭They are equal, OR‬
‭○‬ ‭One of them is 1.‬

‭If these‬‭1‬ ‭conditions are not met, a ValueError is‬‭raised.‬

‭Scenario‬ ‭Description‬ ‭Example‬ ‭Output‬

‭Scalar-Array‬ ‭ scalar is‬


A ‭ rr = np.array([1, 2,‬
a ‭[ 6 7 8]‬
‭broadcast across‬ ‭3]) <br> arr + 5‬
‭the entire array.‬

‭1D-2D (Row)‬ ‭ 1D array can be‬


A ‭ rr2d = np.ones((3,‬
a [‭ [2. 3. 4.]\n [2. 3.‬
‭broadcast across‬ ‭3)) <br> arr1d =‬ ‭4.]\n [2. 3. 4.]]‬
‭rows of a 2D array‬ ‭np.array([1, 2, 3])‬
‭if their lengths‬ ‭<br> arr2d + arr1d‬
‭match the 2D‬
‭array's columns.‬

‭1D-2D (Column)‬ ‭ o broadcast a 1D‬


T ‭ rr1d_col =‬
a [‭ [2. 3. 4.]\n [3. 4.‬
‭array across‬ ‭np.array([[1], [2],‬ ‭5.]\n [4. 5. 6.]]‬
‭columns of a 2D‬ ‭[3]]) <br> arr2d +‬
‭array, explicitly‬ ‭arr1d_col‬
‭reshape the 1D‬
‭array to a column‬
‭vector ((N, 1)).‬

‭np.newaxis‬ ‭ sed to increase‬


U ‭ rr = np.array([1, 2,‬
a [‭ [1]\n [2]\n [3]]‬
‭the dimension of an‬ ‭3]) <br> arr[:,‬ ‭(column vector)‬
‭array by one,‬ ‭np.newaxis]‬
‭typically to enable‬
‭broadcasting.‬

‭Example Usage:‬

‭Python‬

‭import‬‭numpy‬‭as‬‭np‬

‭ rint(‬‭"\n--- Broadcasting ---"‬‭)‬


p
‭arr_a = np.array([[‬‭1‭,‬‬‭2‭,‬‬‭3‭]‬ ,‬
‭[‭4
‬ ‭,‬‬‭5‬‭,‬‭6‭]‬ ])‬‭# Shape (2, 3)‬

‭# Scalar-Array Broadcasting‬
‭print(‬‭f"Array A:\n‬‭{arr_a}‬‭"‬‭)‬
‭print(‬‭f"Array A + 10:\n‬‭{arr_a +‬‭10‬‭}‭"‬ ‬‭)‬

‭# 1D-2D Broadcasting (row-wise)‬


‭arr_b = np.array([‬‭10‬‭,‬‭20‬‭,‬‭30‬‭])‬‭# Shape (3,)‬
‭print(‬‭f"\nArray B (1D):‬‭{arr_b}‬‭"‭)‬ ‬
‭# arr_a (2,3) + arr_b (3,) -> arr_b is broadcast across rows‬
‭print(‬‭f"Array A + Array B:\n‬‭{arr_a + arr_b}‬‭"‭)‬ ‬

‭# 1D-2D Broadcasting (column-wise using np.newaxis)‬


‭arr_c = np.array([‬‭100‬‭,‬‭200‬‭])‬‭# Shape (2,)‬
‭ rr_c_col = arr_c[:, np.newaxis]‬‭# Reshape to (2,‬‭1)‬
a
‭print(‬‭f"\nArray C (1D):‬‭{arr_c}‬‭"‭)‬ ‬
‭print(‬‭f"Array C as column vector:\n‬‭{arr_c_col}‬‭"‬‭)‬
‭# arr_a (2,3) + arr_c_col (2,1) -> arr_c_col is broadcast across columns‬
‭print(‬‭f"Array A + Array C (column-wise):\n‬‭{arr_a +‬‭arr_c_col}‬‭"‬‭)‬

‭ Incompatible shapes (will raise ValueError)‬


#
‭# try:‬
‭# arr_a + np.array([1, 2]) # Shape (2,3) + (2,) - incompatible last dimensions‬
‭# except ValueError as e:‬
‭# print(f"\nError from incompatible shapes: {e}")‬

‭VII. Saving and Loading Arrays‬


‭Persisting your NumPy arrays.‬

‭Method‬ ‭Description‬ ‭Example‬

‭np.save('filename.npy', arr)‬ ‭ aves a single array to a‬


S ‭ p.save('my_array.npy',‬
n
‭binary .npy file.‬ ‭arr_a)‬

‭np.load('filename.npy')‬ ‭ oads an array from an‬


L l‭oaded_arr =‬
‭.npy file.‬ ‭np.load('my_array.npy')‬

‭ p.savez('filename.npz',‬
n ‭ aves multiple arrays into a‬
S ‭ p.savez('multi_arrays.npz',‬
n
‭arr1=arr1, arr2=arr2)‬ ‭single .npz archive.‬ ‭x=arr_a, y=arr_b)‬

‭np.load('filename.npz')‬ ‭ oads a .npz archive.‬


L ‭ ata =‬
d
‭Returns a dictionary-like‬ ‭np.load('multi_arrays.npz')‬
‭object.‬ ‭<br> data['x']‬

‭ p.savetxt('filename.txt',‬
n ‭ aves an array to a text file‬
S ‭ p.savetxt('data.csv', arr_a,‬
n
‭arr, delimiter=' ')‬ ‭(e.g., CSV).‬ ‭delimiter=',')‬

‭ p.loadtxt('filename.txt',‬
n ‭Loads data from a text file.‬ l‭oaded_txt =‬
‭delimiter=' ')‬ ‭np.loadtxt('data.csv',‬
‭delimiter=',')‬

‭Example Usage:‬

‭Python‬

‭import‬‭numpy‬‭as‬‭np‬
‭import‬‭os‬

‭ rint(‬‭"\n--- Saving and Loading Arrays ---"‬‭)‬


p
‭data_to_save = np.arange(‬‭10‬‭).reshape(‬‭2‭,‬‬‭5‬‭)‬
‭print(‬‭f"Data to save:\n‬‭{data_to_save}‬‭"‭)‬ ‬

‭# Save and Load single array (.npy)‬


‭np.save(‬‭'single_array.npy'‬‭, data_to_save)‬
l‭oaded_single = np.load(‬‭'single_array.npy'‬‭)‬
‭print(‬‭f"Loaded from single_array.npy:\n‬‭{loaded_single}‬‭"‭)‬ ‬

‭# Save and Load multiple arrays (.npz)‬


‭data1 = np.array([‬‭10‬‭,‬‭20‬‭,‬‭30‬‭])‬
‭ ata2 = np.array([[‬‭1‬‭,‬‭1‭]‬ , [‬‭2‬‭,‬‭2‬‭]])‬
d
‭np.savez(‬‭'multiple_arrays.npz'‬‭, array1=data1, array2=data2)‬
‭loaded_multiple = np.load(‬‭'multiple_arrays.npz'‬‭)‬
‭print(‬‭f"Loaded from multiple_arrays.npz (array1):‬‭{loaded_multiple[‬‭'array1'‬‭]}‬‭"‭)‬ ‬
‭print(‬‭f"Loaded from multiple_arrays.npz (array2):\n‬‭{loaded_multiple[‬‭'array2'‬‭]}‬‭"‭)‬ ‬
‭loaded_multiple.close()‬‭# Important to close .npz‬‭files after use‬

‭# Save and Load from text file (e.g., CSV)‬


‭text_data = np.array([[‬‭1.1‬‭,‬‭2.2‬‭], [‬‭3.3‬‭,‬‭4.4‬‭]])‬
‭ p.savetxt(‬‭'my_data.csv'‬‭, text_data, delimiter=‬‭','‬‭,‬‭fmt=‬‭'%.2f'‬‭)‬‭# fmt for float precision‬
n
‭loaded_text = np.loadtxt(‬‭'my_data.csv'‬‭, delimiter=‬‭','‬‭)‬
‭print(‬‭f"Loaded from my_data.csv:\n‬‭{loaded_text}‬‭"‬‭)‬

‭# Clean up created files‬


‭os.remove(‬‭'single_array.npy'‬‭)‬
‭ s.remove(‬‭'multiple_arrays.npz'‬‭)‬
o
‭os.remove(‬‭'my_data.csv'‬‭)‬
‭print(‬‭"\nCleaned up created files."‬‭)‬

‭VIII. Advanced Topics‬


‭Concepts for more complex numerical tasks.‬

‭Concept‬ ‭Description‬ ‭Example‬

‭ func (Universal‬
u ‭ lement-wise operations‬
E ‭np.add([1,2],[3,4])‬
‭Functions)‬ ‭on arrays, often highly‬
‭optimized C functions (e.g.,‬
‭np.add, np.sin).‬

‭Vectorization‬ ‭ erforming operations on‬


P ‭ p.array([1,2]) *‬
n
‭entire arrays at once,‬ ‭np.array([3,4]) (fast) vs.‬
‭rather than iterating‬ ‭[a*b for a,b in‬
‭through elements with‬ ‭zip(list1,list2)] (slow)‬
‭Python loops. This is‬
‭NumPy's strength.‬

‭np.where(condition, x, y)‬ ‭ eturns elements chosen‬


R ‭ p.where(arr > 0, arr, 0)‬
n
‭from x or y depending on‬ ‭(replace negatives with 0)‬
‭condition.‬

‭np.unique(arr)‬ ‭ inds unique elements of‬


F ‭np.unique([1,2,2,3,1])‬
‭an array.‬

‭np.clip(arr, min, max)‬ ‭ lip (limit) the values in an‬


C ‭np.clip([-1, 0.5, 2], 0, 1)‬
‭array.‬

‭Masking‬ ‭ sing boolean arrays to‬


U ‭ rr[arr > 5] = 0 (sets‬
a
‭select elements.‬ ‭elements > 5 to 0)‬

‭ tructured Arrays /‬
S ‭ rrays with named fields‬
A ‭ t = np.dtype([('name',‬
d
‭Record Arrays‬ ‭(like a table with columns‬ ‭'S10'), ('age', 'i4')]) <br>‬
‭of different types).‬ ‭data = np.array([('Alice',‬
‭30), ('Bob', 25)], dtype=dt)‬

‭Memory Views vs. Copies‬ ‭ nderstanding when‬


U s‭ = arr[0:2] (view) <br> c =‬
‭operations return a view‬ ‭arr.copy() (copy)‬
‭(sharing memory) or a copy‬
‭(new memory). Slicing‬
‭often returns a view; many‬
‭array methods return‬
‭copies.‬

‭Example Usage:‬

‭Python‬

‭import‬‭numpy‬‭as‬‭np‬

‭ rint(‬‭"\n--- Advanced Topics ---"‬‭)‬


p
‭arr_adv = np.array([-‬‭1‭,‬‬‭0‭,‬‬‭1‬‭,‬‭2‬‭, -‬‭3‭,‬‬‭4‬‭])‬
‭print(‬‭f"Original Array:‬‭{arr_adv}‬‭"‬‭)‬
‭# np.where‬
‭ ositive_only = np.where(arr_adv >‬‭0‬‭, arr_adv,‬‭0‭)‬ ‬
p
‭print(‬‭f"Elements > 0, else 0:‬‭{positive_only}‬‭"‬‭)‬

‭# np.unique‬
‭ nique_elements = np.unique(np.array([‬‭1‬‭,‬‭2‭,‬‬‭2‭,‬‬‭3‭,‬‬‭1‭,‬‬‭4‬‭,‬‭3‭]‬ ))‬
u
‭print(‬‭f"Unique elements:‬‭{unique_elements}‬‭"‭)‬ ‬

‭# np.clip‬
‭ lipped_arr = np.clip(arr_adv, -‬‭2‭,‬‬‭2‬‭)‬
c
‭print(‬‭f"Clipped between -2 and 2:‬‭{clipped_arr}‬‭"‭)‬ ‬

‭# Masking (boolean indexing for assignment)‬


‭mask = arr_adv <‬‭0‬
‭ rr_adv[mask] =‬‭99‬‭# Set negative values to 99‬
a
‭print(‬‭f"Array after masking (negatives set to 99):‬‭{arr_adv}‬‭"‭)‬ ‬

‭# Structured Arrays‬
‭dt = np.dtype([(‬‭'name'‬‭,‬‭'U10'‬‭), (‬‭'age'‬‭,‬‭'i4'‬‭), (‬‭'gpa'‬‭,‬‭'f8'‬‭)])‬‭# U10: unicode string up to 10 chars, i4:‬
‭4-byte int, f8: 8-byte float‬
‭students = np.array([(‬‭"Alice"‬‭,‬‭21‬‭,‬‭3.8‬‭), (‬‭"Bob"‬‭,‬‭22‬‭,‬‭3.5‬‭)], dtype=dt)‬
‭ rint(‬‭f"\nStructured Array:\n‬‭{students}‬‭"‭)‬ ‬
p
‭print(‬‭f"Names:‬‭{students[‬‭'name'‬‭]}‬‭"‬‭)‬
‭print(‬‭f"Ages > 21:‬‭{students[students[‬‭'age'‬‭] >‬‭21‬‭][‬‭'name'‬‭]}‬‭"‭)‬ ‬

‭ Vectorization (conceptual example)‬


#
‭# Python loop (less efficient for large arrays)‬
‭list1 = [i‬‭for‬‭i‬‭in‬‭range‬‭(‬‭1000000‬‭)]‬
‭list2 = [i‬‭for‬‭i‬‭in‬‭range‬‭(‬‭1000000‬‭)]‬
‭# %timeit [list1[i] + list2[i] for i in range(len(list1))] # roughly 100ms‬

‭# NumPy vectorized operation (much more efficient)‬


‭np_arr1 = np.arange(‬‭1000000‬‭)‬
‭np_arr2 = np.arange(‬‭1000000‬‭)‬
‭# %timeit np_arr1 + np_arr2 # roughly 1ms (100x faster)‬
‭print(‬‭"\nVectorization: NumPy operations are significantly‬‭faster for large datasets than Python loops."‬‭)‬

‭ his cheat sheet should give you a solid foundation for working with NumPy arrays and‬
T
‭performing various numerical computations efficiently!‬

‭ ources‬
S
‭1.‬‭https://github.com/Vipulbhansali/Python-Tutorial‬

You might also like