NumPy Cheat Sheet
Creating NumPy Arrays Array Attributes
arr = [Link]([1, 2, 3, 4, 5]) shape = [Link] # Shape of the array
zeros = [Link](5) # Array of zeros dtype = [Link] # Data type of the array
ones = [Link](5) # Array of ones size = [Link] # Number of elements in the array
empty = [Link](5) # Array of uninitialized values dim = [Link] # Number of dimensions
range_arr = [Link](0, 10, 2) # Array with values
from 0 to 10 with step 2 Accessing Elements
linspace_arr = [Link](0, 1, 5) # Array with 5 value = arr[2] # Access element at index 2
evenly spaced values between 0 and 1 slicing = arr[1:4] # Slicing from index 1 to 3 (4 is
random_arr = [Link](3, 3) # 3x3 array of exclusive)
random values between 0 and 1 indexing = arr[[0, 2, 4]] # Accessing elements by
index
Basic Operations
addition = arr + 2 # Add 2 to each element Array Functions
subtraction = arr - 2 # Subtract 2 from each mean = [Link](arr) # Mean (average) of array
element median = [Link](arr) # Median of array
multiplication = arr * 2 # Multiply each element by2 sum_arr = [Link](arr) # Sum of array
division = arr / 2 # Divide each element by 2 min_val = [Link](arr) # Minimum value in array
power = [Link](arr, 2) # Raise each element to max_val = [Link](arr) # Maximum value in array
the power of 2
Reshaping Arrays Combining Arrays
reshaped = [Link](2, 3) # Reshape to a 2x3 concatenated = [Link]((arr, arr)) #
array Concatenate two arrays
flattened = [Link]() # Flatten the array stacked = [Link]((arr, arr), axis=0) # Stack arrays
transposed = arr.T # Transpose the array along a new axis
Element-wise Comparison Filtering with Boolean Indexing
boolean_arr = arr > 3 # Returns a boolean array with filtered_arr = arr[arr > 3] # Get elements greater
the comparison result than 3
Element-wise Operations Universal Functions
result = [Link](arr) # Element-wise sine function ufunc = [Link](arr, 2) # Universal function for
result = [Link](arr) # Element-wise addition
exponentiation ufunc = [Link](arr) # Universal function for square
result = [Link](arr) # Element-wise square root root
ufunc = [Link](arr) # Universal function for natural
logarithm
Unique Values Element-wise Conditional Operations
unique_vals = [Link](arr) # Get unique values in conditional_arr = [Link](arr > 3, arr, 0) # Replace
the array values less than 3 with 0
Saving and Loading Arrays Dot Product
[Link]('my_array.npy', arr) # Save array to a file dot_product = [Link](arr1, arr2) # Dot product of
loaded_arr = [Link]('my_array.npy') # Load array two arrays
from a file
Copying Arrays
copy = [Link]() # Create a deep copy of the Matrix Operations
array matrix_product = [Link](matrix1, matrix2) #
view = [Link]() # Create a view of the array Matrix multiplication
(shares data)
Sorting Linear Algebra
sorted_arr = [Link](arr) # Sort the array in determinant = [Link](matrix) #
ascending order Determinant of a matrix
indices = [Link](arr) # Indices that would sort eigenvalues, eigenvectors = [Link](matrix) #
the array Eigenvalues and eigenvectors
inverse_matrix = [Link](matrix) # Inverse of
a matrix
Stacking Arrays
Element-wise Arithmetic Operations vstack = [Link]((arr1, arr2)) # Stack arrays
add_arrays = [Link](arr, arr) vertically
hstack = [Link]((arr1, arr2)) # Stack arrays
horizontally
Element-wise addition Random Number Generation
subtract_arrays = [Link](arr, arr) # Element- random_int = [Link](1, 10, size=(3, 3)) #
wise subtraction 3x3 random integers between 1 and 10
multiply_arrays = [Link](arr, arr) # Element- normal_dist = [Link](0, 1, size=(3, 3)) #
wise multiplication 3x3 array of random numbers from a normal
divide_arrays = [Link](arr, arr) # Element-wise distribution
division
Splitting Arrays Statistics
split_arr = [Link](arr, 3) # Split array into 3 equal std_dev = [Link](arr) # Standard deviation
parts variance = [Link](arr) # Variance
hsplit_arr = [Link](matrix, 2) # Horizontally split
a matrix into 2 parts
Trigonometric Functions Constants
sine_values = [Link](arr) # Sine values pi = [Link] # The mathematical constant π
cosine_values = [Link](arr) # Cosine values e = np.e # The mathematical constant e
tangent_values = [Link](arr) # Tangent values
Broadcasting
arr_broadcast = arr + 3 # Broadcasting a scalar value to the array
Finding Index
index = [Link](arr == 3) # Find the index of the value 3 in the array
Element-wise Absolute Values Rounding
abs_arr = [Link](arr) # Element-wise absolute rounded_arr = [Link](arr, decimals=2) # Round
values elements to a specified number of decimals
Indexing and Slicing with Multi-dimensional
Arrays
Concatenating Strings in NumPy Arrays matrix = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
string_array = [Link](['Hello', 'World']) element = matrix[1, 2] # Access a specific element
concatenated_str = [Link](string_array, '!') row = matrix[1, :] # Access the entire second row
column = matrix[:, 2]
# Access the entire third column
Element-wise Logical Operations
Reshaping and Flattening logical_and = np.logical_and(arr > 2, arr < 5) #
raveled = [Link]() # Flatten the array Element-wise logical AND
reshaped = [Link](2, -1) # Reshape with one logical_or = np.logical_or(arr > 2, arr < 5) #
dimension inferred Element-wise logical OR
logical_not = np.logical_not(arr > 2) # Element-
wise logical NOT
Cumulative Sum and Product
cumulative_sum = [Link](arr) # Cumulative Histogram
sum hist, bin_edges = [Link](arr, bins=5) #
cumulative_product = [Link](arr) # Compute histogram
Cumulative product
Interpolation
Repeat and Tile interp_val = [Link](3.5, [3, 4], [30, 40]) # Linear
repeated = [Link](arr, 3) # Repeat elements interpolation
tiled = [Link](arr, 3) # Tile the array
Finding Unique Indices Element-wise Floor and Ceiling
unique_indices = np.unique_indices(arr) # Indices of floor_values = [Link](arr) # Element-wise floor
unique values function
ceil_values = [Link](arr) # Element-wise ceiling
function
Bitwise Operations NaN Handling
bitwise_and = np.bitwise_and(arr1, arr2) arr_with_nan = [Link]([1, 2, [Link], 4, 5])
# Bitwise AND
bitwise_or = np.bitwise_or(arr1, arr2) nan_mean = [Link](arr_with_nan) # Mean
# Bitwise OR ignoring NaN values
bitwise_xor = np.bitwise_xor(arr1, arr2)# Bitwise
XOR Linear Space
linear_space = [Link](0, 1, num=11) # Create 11
Save and Load as Text evenly spaced values between 0 and 1
[Link]('my_array.txt', arr, delimiter=',')
# Save array as a text file # Clip Values
loaded_arr = [Link]('my_array.txt', clipped_arr = [Link](arr, a_min=2, a_max=4) # Clip
delimiter=',') # Load array from a text file values below 2 to 2 and above 4 to 4
# Broadcasting with Arrays of Different Shapes # Sorting with Indices
A = [Link]([1, 2, 3]) sorted_indices = [Link](arr) # Indices that would
B = [Link]([[4], [5], [6]]) sort the array
broadcasted = A + B
Exponents and Logarithms Custom Functions
exponential = [Link](arr) # Exponential function custom_function = [Link](lambda x: x ** 2)
logarithm = [Link](arr) # Natural logarithm result = custom_function(arr)
Element-wise Logical XOR Reversing an Array
logical_xor = np.logical_xor(arr > 2, arr < 5) # reversed_arr = [Link](arr) # Reverse the order of
Element-wise logical XOR elements in an array
Bitwise Shifts Masked Arrays
left_shift = np.left_shift(4, 2) # Bitwise left shift masked_arr = [Link].masked_where(arr < 3, arr) #
right_shift = np.right_shift(16, 2) # Bitwise right Create a masked array based on a condition
shift
Set Operations # Working with Complex Numbers
set_intersection = np.intersect1d(arr1, arr2) # complex_arr = [Link]([1 + 2j, 3 + 4j, 5 + 6j])
Intersection of two arrays real_part = [Link](complex_arr) # Real part of
set_union = np.union1d(arr1, arr2) # Union of two complex numbers
arrays imaginary_part = [Link](complex_arr) #
set_difference = np.setdiff1d(arr1, arr2) # Imaginary part of complex numbers
Difference of two arrays conjugate = [Link](complex_arr) # Complex
set_symmetric_difference = np.setxor1d(arr1, arr2) conjugate
# Symmetric difference of two arrays
Selecting Values from Multiple Arrays Polynomials
where_condition = (arr > 2) # Boolean condition coefficients = [1, -2, 0, 3]
selected_values = [Link]([where_condition, arr < poly = np.poly1d(coefficients) # Create a polynomial
5], [arr, arr * 2], default=0) roots = [Link](coefficients) # Find roots of the
polynomial
# Creating a Range of Dates Masked Arrays
date_range = [Link]('2023-01-01', '2023-01-11', masked_array = [Link].masked_where(arr < 3, arr) #
dtype='datetime64[D]') Create a masked array based on a condition
Shuffling an Array Outer Product
shuffled_arr = [Link](arr) # outer_product = [Link](arr1, arr2) # Compute the
Randomly shuffle the elements outer product of two arrays
Element-wise Hyperbolic Functions Finding NaN Values
sinh_values = [Link](arr) # Hyperbolic sine values nan_indices = [Link](arr) # Get indices of NaN
cosh_values = [Link](arr) # Hyperbolic cosine values in an array
values
tanh_values = [Link](arr) # Hyperbolic tangent # Extracting Diagonal Elements
values diagonal = [Link](arr) # Extract the diagonal
elements of a 2D array
Generating a Mesh Grid Element-wise Floor Division and Modulo
x = [Link](0, 5) floor_div = np.floor_divide(arr, 2) # Element-wise
y = [Link](0, 3) floor division
X, Y = [Link](x, y) # Create coordinate modulo = [Link](arr, 3) # Element-wise modulo
matrices for vectorized evaluations operation
Element-wise Hyperbolic Inverse Functions Handling Complex Numbers
arcsinh_values = [Link](arr) # Inverse complex_arr = [Link]([1 + 2j, 3 - 4j, 5 + 6j])
hyperbolic sine magnitude = [Link](complex_arr) # Magnitude
arccosh_values = [Link](arr + 1) # Inverse (absolute value) of complex numbers
hyperbolic cosine phase = [Link](complex_arr) # Phase angle of
arctanh_values = [Link](arr * 0.8) # Inverse complex numbers
hyperbolic tangent
Element-wise Rounding Functions
round_up = [Link](arr) # Round up to the nearest Rotating a Multi-dimensional Array
integer rotated_array = np.rot90(multi_dim_arr, k=2) #
round_down = [Link](arr) # Round down to the Rotate the 2D array 180 degrees
nearest integer
Polynomial Fitting Element-wise Logical NOR and NAND
coefficients = [Link](x, y, deg=2) # Fit a logical_nor = np.logical_not(np.logical_or(arr > 2, arr
polynomial of degree 2 to data < 5)) # Element-wise logical NOR
logical_nand = np.logical_not(np.logical_and(arr > 2,
arr < 5)) # Element-wise logical NAND
Element-wise Heaviside Step Function Modifying Data Type
heaviside = [Link](arr - 3, 0.5) # Heaviside modified_arr = [Link](np.float64) # Change
step function data type to float64
Modifying Data Type Rounding to the Nearest Integer
modified_arr = [Link](np.float64) # Change rounded_int = [Link](arr) # Round to the nearest
data type to float64 integer
Element-wise Absolute Value for Complex Numbers Creating an Identity Matrix with a Custom
abs_complex = [Link](complex_arr) Diagonal
# Element-wise absolute value for complex custom_identity = [Link](3, k=1) # Create a 3x3
numbers identity matrix with a shifted diagonal
Binning Data
Dot Product for Multi-dimensional Arrays bin_counts, bin_edges = [Link](arr, bins=[0,
dot_product_multi_dim = 2, 4, 6, 8])
[Link](multi_dim_arr1, multi_dim_arr2,
axes=([1, 2], [0, 1])) Element-wise Logistic Sigmoid Function
logistic_sigmoid = 1 / (1 + [Link](-arr)
Trigonometric Functions for Complex Numbers Element-wise Hyperbolic Secant Function
sine_complex = [Link](complex_arr) # Sine of sech_values = 1 / [Link](arr)
complex numbers
cosine_complex = [Link](complex_arr) # Cosine of Element-wise Cosecant Function
complex numbers csc_values = 1 / [Link](arr)
Working with Binary Representation Calculating Mean Absolute Error (MAE)
binary_repr = np.binary_repr(10) # Convert integer mae = [Link]([Link](predicted - actual))
to binary representation
from_binary_repr = int(np.binary_repr(1010), 2) # # Calculating Root Mean Square Error (RMSE)
Convert binary string to integer rmse = [Link]([Link]((predicted - actual)**2))
Prepared by:
Chushritha Bandaru