Numpy Cheat Sheet
Numpy Cheat Sheet
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.
Python
importnumpyasnp
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.
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
importnumpyasnp
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}")
identity_matrix = np.eye(4)
print(f"Identity Matrix (4x4):\n{identity_matrix}")
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}")
arr.T he transposed
T arr2d.T [[1 3]\n [2 4]]
array.
Example Usage:
Python
importnumpyasnp
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}")
rr2d =
a 2
np.array([[1,2],[3,4]
]) <br> arr2d[0, 1]
Example Usage:
Python
importnumpyasnp
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]
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.
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 Inserts values along p.insert(arr1d, 1,
n [10 15 20 30 40 50]
values, axis=None) the given axis 15)
before the given
indices.
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
importnumpyasnp
# 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 into3 equal parts
print(f"Split array:{split_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}")
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.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).
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).
rr.mean(axis=Non
a ean of all
M arr.mean() 2.5
e) elements or along
an axis.
rr.argmin(axis=No
a Index of minimum arr.argmin() 0 (flattened index)
ne) element.
rr.argmax(axis=No
a Index of maximum arr.argmax(axis=1) [ 1 1] (index of max
ne) element. in each row)
Example Usage:
Python
importnumpyasnp
importmath
# 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)}")
Example Usage:
Python
importnumpyasnp
# Scalar-Array Broadcasting
print(f"Array A:\n{arr_a}")
print(f"Array A + 10:\n{arr_a +10}" )
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)
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. loaded_txt =
delimiter=' ') np.loadtxt('data.csv',
delimiter=',')
Example Usage:
Python
importnumpyasnp
importos
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).
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)
Example Usage:
Python
importnumpyasnp
# 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}")
# 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']}")
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