0% found this document useful (0 votes)
13 views6 pages

numpy cheet sheet 6 page

This document is a comprehensive cheat sheet for NumPy, covering various functionalities such as creating and manipulating arrays, performing mathematical operations, and handling data types. It includes sections on array attributes, basic operations, reshaping, combining, and sorting arrays, as well as advanced topics like linear algebra, statistics, and random number generation. Additionally, it provides examples for element-wise operations, broadcasting, and working with complex numbers.

Uploaded by

sivamugunthan342
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)
13 views6 pages

numpy cheet sheet 6 page

This document is a comprehensive cheat sheet for NumPy, covering various functionalities such as creating and manipulating arrays, performing mathematical operations, and handling data types. It includes sections on array attributes, basic operations, reshaping, combining, and sorting arrays, as well as advanced topics like linear algebra, statistics, and random number generation. Additionally, it provides examples for element-wise operations, broadcasting, and working with complex numbers.

Uploaded by

sivamugunthan342
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/ 6

NumPy Cheat Sheet

Creating NumPy Arrays Array Attributes


arr = np.array([1, 2, 3, 4, 5]) shape = arr.shape # Shape of the array
zeros = np.zeros(5) # Array of zeros dtype = arr.dtype # Data type of the array
ones = np.ones(5) # Array of ones size = arr.size # Number of elements in the array
empty = np.empty(5) # Array of uninitialized values dim = arr.ndim # Number of dimensions
range_arr = np.arange(0, 10, 2) # Array with values
from 0 to 10 with step 2 Accessing Elements
linspace_arr = np.linspace(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 = np.random.rand(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 = np.mean(arr) # Mean (average) of array
element median = np.median(arr) # Median of array
multiplication = arr * 2 # Multiply each element by2 sum_arr = np.sum(arr) # Sum of array
division = arr / 2 # Divide each element by 2 min_val = np.min(arr) # Minimum value in array
power = np.power(arr, 2) # Raise each element to max_val = np.max(arr) # Maximum value in array
the power of 2

Reshaping Arrays Combining Arrays


reshaped = arr.reshape(2, 3) # Reshape to a 2x3 concatenated = np.concatenate((arr, arr)) #
array Concatenate two arrays
flattened = arr.flatten() # Flatten the array stacked = np.stack((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 = np.sin(arr) # Element-wise sine function ufunc = np.add(arr, 2) # Universal function for
result = np.exp(arr) # Element-wise addition
exponentiation ufunc = np.sqrt(arr) # Universal function for square
result = np.sqrt(arr) # Element-wise square root root
ufunc = np.log(arr) # Universal function for natural
logarithm

Unique Values Element-wise Conditional Operations


unique_vals = np.unique(arr) # Get unique values in conditional_arr = np.where(arr > 3, arr, 0) # Replace
the array values less than 3 with 0
Saving and Loading Arrays Dot Product
np.save('my_array.npy', arr) # Save array to a file dot_product = np.dot(arr1, arr2) # Dot product of
loaded_arr = np.load('my_array.npy') # Load array two arrays
from a file
Copying Arrays
copy = arr.copy() # Create a deep copy of the Matrix Operations
array matrix_product = np.matmul(matrix1, matrix2) #
view = arr.view() # Create a view of the array Matrix multiplication
(shares data)

Sorting Linear Algebra


sorted_arr = np.sort(arr) # Sort the array in determinant = np.linalg.det(matrix) #
ascending order Determinant of a matrix
indices = np.argsort(arr) # Indices that would sort eigenvalues, eigenvectors = np.linalg.eig(matrix) #
the array Eigenvalues and eigenvectors
inverse_matrix = np.linalg.inv(matrix) # Inverse of
a matrix

Stacking Arrays
Element-wise Arithmetic Operations vstack = np.vstack((arr1, arr2)) # Stack arrays
add_arrays = np.add(arr, arr) vertically
hstack = np.hstack((arr1, arr2)) # Stack arrays
horizontally

Element-wise addition Random Number Generation


subtract_arrays = np.subtract(arr, arr) # Element- random_int = np.random.randint(1, 10, size=(3, 3)) #
wise subtraction 3x3 random integers between 1 and 10
multiply_arrays = np.multiply(arr, arr) # Element- normal_dist = np.random.normal(0, 1, size=(3, 3)) #
wise multiplication 3x3 array of random numbers from a normal
divide_arrays = np.divide(arr, arr) # Element-wise distribution
division

Splitting Arrays Statistics


split_arr = np.split(arr, 3) # Split array into 3 equal std_dev = np.std(arr) # Standard deviation
parts variance = np.var(arr) # Variance
hsplit_arr = np.hsplit(matrix, 2) # Horizontally split
a matrix into 2 parts

Trigonometric Functions Constants


sine_values = np.sin(arr) # Sine values pi = np.pi # The mathematical constant π
cosine_values = np.cos(arr) # Cosine values e = np.e # The mathematical constant e
tangent_values = np.tan(arr) # Tangent values
Broadcasting
arr_broadcast = arr + 3 # Broadcasting a scalar value to the array

Finding Index
index = np.where(arr == 3) # Find the index of the value 3 in the array
Element-wise Absolute Values Rounding
abs_arr = np.abs(arr) # Element-wise absolute rounded_arr = np.round(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 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
string_array = np.array(['Hello', 'World']) element = matrix[1, 2] # Access a specific element
concatenated_str = np.char.add(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 = arr.ravel() # Flatten the array Element-wise logical AND
reshaped = arr.reshape(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 = np.cumsum(arr) # Cumulative Histogram
sum hist, bin_edges = np.histogram(arr, bins=5) #
cumulative_product = np.cumprod(arr) # Compute histogram
Cumulative product

Interpolation
Repeat and Tile interp_val = np.interp(3.5, [3, 4], [30, 40]) # Linear
repeated = np.repeat(arr, 3) # Repeat elements interpolation
tiled = np.tile(arr, 3) # Tile the array

Finding Unique Indices Element-wise Floor and Ceiling


unique_indices = np.unique_indices(arr) # Indices of floor_values = np.floor(arr) # Element-wise floor
unique values function
ceil_values = np.ceil(arr) # Element-wise ceiling
function

Bitwise Operations NaN Handling


bitwise_and = np.bitwise_and(arr1, arr2) arr_with_nan = np.array([1, 2, np.nan, 4, 5])
# Bitwise AND
bitwise_or = np.bitwise_or(arr1, arr2) nan_mean = np.nanmean(arr_with_nan) # Mean
# Bitwise OR ignoring NaN values
bitwise_xor = np.bitwise_xor(arr1, arr2)# Bitwise
XOR Linear Space
linear_space = np.linspace(0, 1, num=11) # Create 11
Save and Load as Text evenly spaced values between 0 and 1
np.savetxt('my_array.txt', arr, delimiter=',')
# Save array as a text file # Clip Values
loaded_arr = np.loadtxt('my_array.txt', clipped_arr = np.clip(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 = np.array([1, 2, 3]) sorted_indices = np.argsort(arr) # Indices that would
B = np.array([[4], [5], [6]]) sort the array
broadcasted = A + B

Exponents and Logarithms Custom Functions


exponential = np.exp(arr) # Exponential function custom_function = np.vectorize(lambda x: x ** 2)
logarithm = np.log(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 = np.flip(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 = np.ma.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 = np.array([1 + 2j, 3 + 4j, 5 + 6j])
Intersection of two arrays real_part = np.real(complex_arr) # Real part of
set_union = np.union1d(arr1, arr2) # Union of two complex numbers
arrays imaginary_part = np.imag(complex_arr) #
set_difference = np.setdiff1d(arr1, arr2) # Imaginary part of complex numbers
Difference of two arrays conjugate = np.conj(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 = np.select([where_condition, arr < poly = np.poly1d(coefficients) # Create a polynomial
5], [arr, arr * 2], default=0) roots = np.roots(coefficients) # Find roots of the
polynomial
# Creating a Range of Dates Masked Arrays
date_range = np.arange('2023-01-01', '2023-01-11', masked_array = np.ma.masked_where(arr < 3, arr) #
dtype='datetime64[D]') Create a masked array based on a condition

Shuffling an Array Outer Product


shuffled_arr = np.random.permutation(arr) # outer_product = np.outer(arr1, arr2) # Compute the
Randomly shuffle the elements outer product of two arrays

Element-wise Hyperbolic Functions Finding NaN Values


sinh_values = np.sinh(arr) # Hyperbolic sine values nan_indices = np.isnan(arr) # Get indices of NaN
cosh_values = np.cosh(arr) # Hyperbolic cosine values in an array
values
tanh_values = np.tanh(arr) # Hyperbolic tangent # Extracting Diagonal Elements
values diagonal = np.diag(arr) # Extract the diagonal
elements of a 2D array

Generating a Mesh Grid Element-wise Floor Division and Modulo


x = np.arange(0, 5) floor_div = np.floor_divide(arr, 2) # Element-wise
y = np.arange(0, 3) floor division
X, Y = np.meshgrid(x, y) # Create coordinate modulo = np.mod(arr, 3) # Element-wise modulo
matrices for vectorized evaluations operation

Element-wise Hyperbolic Inverse Functions Handling Complex Numbers


arcsinh_values = np.arcsinh(arr) # Inverse complex_arr = np.array([1 + 2j, 3 - 4j, 5 + 6j])
hyperbolic sine magnitude = np.abs(complex_arr) # Magnitude
arccosh_values = np.arccosh(arr + 1) # Inverse (absolute value) of complex numbers
hyperbolic cosine phase = np.angle(complex_arr) # Phase angle of
arctanh_values = np.arctanh(arr * 0.8) # Inverse complex numbers
hyperbolic tangent

Element-wise Rounding Functions


round_up = np.ceil(arr) # Round up to the nearest Rotating a Multi-dimensional Array
integer rotated_array = np.rot90(multi_dim_arr, k=2) #
round_down = np.floor(arr) # Round down to the Rotate the 2D array 180 degrees
nearest integer

Polynomial Fitting Element-wise Logical NOR and NAND


coefficients = np.polyfit(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 = np.heaviside(arr - 3, 0.5) # Heaviside modified_arr = arr.astype(np.float64) # Change
step function data type to float64

Modifying Data Type Rounding to the Nearest Integer


modified_arr = arr.astype(np.float64) # Change rounded_int = np.rint(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 = np.abs(complex_arr) Diagonal

# Element-wise absolute value for complex custom_identity = np.eye(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 = np.histogram(arr, bins=[0,
dot_product_multi_dim = 2, 4, 6, 8])
np.tensordot(multi_dim_arr1, multi_dim_arr2,
axes=([1, 2], [0, 1])) Element-wise Logistic Sigmoid Function
logistic_sigmoid = 1 / (1 + np.exp(-arr)

Trigonometric Functions for Complex Numbers Element-wise Hyperbolic Secant Function


sine_complex = np.sin(complex_arr) # Sine of sech_values = 1 / np.cosh(arr)
complex numbers
cosine_complex = np.cos(complex_arr) # Cosine of Element-wise Cosecant Function
complex numbers csc_values = 1 / np.sin(arr)

Working with Binary Representation Calculating Mean Absolute Error (MAE)


binary_repr = np.binary_repr(10) # Convert integer mae = np.mean(np.abs(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 = np.sqrt(np.mean((predicted - actual)**2))

Prepared by:

Chushritha Bandaru

You might also like