0% found this document useful (0 votes)
2 views9 pages

arshdeep_numpy

The Numpy Cheat Sheet provides a comprehensive overview of key NumPy functionalities, including array slicing, performance tips, basic operations, and handling NaN values. It emphasizes the importance of using vectorized operations and in-place modifications to enhance performance, as well as techniques for array creation and manipulation. Additionally, it covers mathematical functions and linear algebra operations, highlighting the advantages of NumPy over traditional Python lists.

Uploaded by

sanboulimounir14
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)
2 views9 pages

arshdeep_numpy

The Numpy Cheat Sheet provides a comprehensive overview of key NumPy functionalities, including array slicing, performance tips, basic operations, and handling NaN values. It emphasizes the importance of using vectorized operations and in-place modifications to enhance performance, as well as techniques for array creation and manipulation. Additionally, it covers mathematical functions and linear algebra operations, highlighting the advantages of NumPy over traditional Python lists.

Uploaded by

sanboulimounir14
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/ 9

Numpy Cheat Sheet

by Arshdeep via cheatography.com/201979/cs/42960/

Array Slicing Perfor​mance Tips and Tricks (cont)

Defiti​‐ Array slicing allows you to extract specific parts of an array. It works
Avoid Be mindful of unnece​ssary array copies, especially
nition similarly to list slicing in Python. Copies when working with large datasets. NumPy arrays
Example arr = np.arr​ay([0, 1, 2, 3, 4, 5]) share memory when possible, but certain operations
may create copies, which can impact perfor​mance and
Slicing arr[st​art​:st​op:​step]
memory usage.
syntax
Use In- Whenever feasible, use in-place operations (+=, *=,
Basic slice_1 = arr[1:4] # [1, 2, 3]
Place etc.) to modify arrays without creating new ones. This
slicing slice_2 = arr[:3] # [0, 1, 2]
Operations reduces memory overhead and can improve perfor​‐
slice_3 = arr[3:] # [3, 4, 5]
mance.
Negative slice_4 = arr[-3:] # [3, 4, 5]
Memory Understand how memory layout affects perfor​mance,
indexing slice_5 = arr[:-2] # [0, 1, 2] Layout especially for large arrays. NumPy arrays can be
Step slice_6 = arr[::2] # [0, 2, 4] stored in different memory orders (C-order vs. Fortra​n-
slicing slice_7 = arr[1::2] # [1, 3, 5] o​rder). Choosing the approp​riate memory layout can
sometimes lead to better perfor​mance, especially
Reverse slice_8 = arr[::-1] # [5, 4, 3, 2, 1, 0]
when performing operations along specific axes.
array
Data Choose approp​riate data types for your arrays to
Slicing arr_2d = np.arr​ay([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Types minimize memory usage and improve perfor​mance.
2D
Using smaller data types (e.g., np.float32 instead of
arrays slice_9 = arr_2d[:2, 1:] # [[2, 3], [5, 6]]
np.flo​at64) can reduce memory overhead and may
lead to faster comput​ations, especially on platforms
Perfor​mance Tips and Tricks
with limited memory bandwidth.
Vector​‐ Utilize NumPy's built-in vectorized operations whenever
NumExpr Consider using specia​lized libraries like NumExpr or
ization possible. These operations are optimized and signif​‐
and Numba for perfor​man​ce-​cri​tical sections of your code.
icantly faster than equivalent scalar operat​ions.
Numba These libraries can often provide signif​icant speedups
Avoiding Minimize the use of Python loops when working with by compiling expres​sions or functions to native
Loops NumPy arrays. Instead, try to express operations as machine code.
array operat​ions. Loops in Python can be slow compared
to vectorized operat​ions.
Use Take advantage of NumPy's broadc​asting rules to
Broadc​‐ perform operations on arrays of different shapes effici​‐
asting ently. Broadc​asting allows NumPy to work with arrays of
different sizes without making unnece​ssary copies of
data.

By Arshdeep Not published yet. Sponsored by Readable.com


cheatography.com/arshdeep/ Last updated 6th April, 2024. Measure your website readability!
Page 1 of 9. https://readable.com
Numpy Cheat Sheet
by Arshdeep via cheatography.com/201979/cs/42960/

Perfor​mance Tips and Tricks (cont) Basic Operations

Parall​‐ NumPy itself doesn't provide built-in parall​elism, but you Addition array1 + array2
elism can leverage multi-​thr​eading or multi-​pro​cessing libraries Subtra​ction array1 - array2
like concur​ren​t.f​utures or joblib to parall​elize certain
Multip​lic​ation array1 * array2
operat​ions, especially when working with large datasets
Division array1 / array2
or comput​ati​onally intensive tasks.
Floor Division array1 // array2
Profiling Use profiling tools like cProfile or specia​lized profilers
such as line_p​rofiler or memory​_pr​ofiler to identify perfor​‐ Modulus array1 % array2
mance bottle​necks in your code. Optimizing code based Expone​nti​ation array1 ** array2
on actual profiling results can lead to more signif​icant
Absolute np.abs​(array)
perfor​mance improv​ements.
Negative -array

Array Concat​enation and Splitting Reciprocal 1 / array

Sum np.sum​(array)
Concat​‐ array1 = np.arr​ay([[1, 2, 3], [4, 5, 6]])
enation array2 = np.arr​ay([[7, 8, 9]]) Minimum np.min​(array)
Maximum
concatenated_array = np.con​cat​ena​te(​(ar​ray1, array2), axis np.max​(array)
=0) Mean np.mea​n(a​rray)
# vertically
Median np.med​ian​(array)
print(concatenated_array)
Standard Deviation np.std​(array)
numpy.c​ Concat​enates arrays along a specified axis.
Variance np.var​(array)
on​cat​‐
Dot Product np.dot​(ar​ray1, array2)
enate()
Cross Product np.cro​ss(​array1, array2)
numpy.v​ Stack arrays vertically and horizo​ntally, respec​tively.
st​ack()
NaN Handling
and
numpy.h​ Identi​‐ Use np.isnan() function to check for NaN values in an
st​ack() fying array.
numpy.d​ Stack arrays depth-​wise. NaNs
st​ack() Removing Use np.isnan() to create a boolean mask, then use
Splitting NaNs
split_​arrays = np.spl​it(​con​cat​ena​ted​_array, boolean indexing to select non-NaN values.

[2], Replacing Use np.nan​_to​_num() to replace NaNs with a specified


axis=0) NaNs value. Use np.nan​mean(), np.nan​med​ian(), etc., to
# split after the second row compute mean, median, etc., ignoring NaNs.
print(split_arrays)

numpy.s​ Split an array into multiple sub-arrays along a specified axis.


plit()
numpy.h​ Split arrays horizo​ntally and vertic​ally, respec​tively.
sp​lit()
and
numpy.v​
sp​lit()
numpy.d​ Split arrays depth-​wise.
sp​lit()

By Arshdeep Not published yet. Sponsored by Readable.com


cheatography.com/arshdeep/ Last updated 6th April, 2024. Measure your website readability!
Page 2 of 9. https://readable.com
Numpy Cheat Sheet
by Arshdeep via cheatography.com/201979/cs/42960/

NaN Handling (cont) Mathem​atical Functions

Interp​‐ Sure, here's a short content for "NaN Handli​ng" on your Definition NumPy provides a wide range of mathem​atical
olating NumPy cheat sheet: NaN Handling: Identi​fying NaNs: functions that operate elemen​t-wise on arrays,
NaNs Use np.isnan() function to check for NaN values in an allowing for efficient comput​ation across large
array. Removing NaNs: Use np.isnan() to create a datasets.
boolean mask, then use boolean indexing to select Trigon​‐ np.sin(), np.cos(), np.tan(), np.arc​sin(), np.arc​cos(),
non-NaN values. Replacing NaNs: Use np.nan​_to​‐ ometric np.arc​tan()
_num() to replace NaNs with a specified value. Use Functions
np.nan​mean(), np.nan​med​ian(), etc., to compute
Hyperbolic np.sinh(), np.cosh(), np.tanh(), np.arc​sinh(), np.arc​‐
mean, median, etc., ignoring NaNs. Interp​olating NaNs
Functions cosh(), np.arc​tanh()
Ignoring Many NumPy functions have NaN-aware counte​rparts,
Expone​ntial np.exp(), np.log(), np.log2(), np.log10()
NaNs in like np.nan​mean(), np.nan​sum(), etc., that ignore
and Logari​‐
Operations NaNs in comput​ations.
thmic
Handling Aggreg​ation functions (np.sum(), np.mean(), etc.) Functions
NaNs in typically return NaN if any NaNs are present in the
Rounding np.rou​nd(), np.flo​or(), np.ceil(), np.trunc()
Aggreg​‐ input array. Use skipna​=True parameter in pandas
Absolute np.abs()
ations DataFrame functions for NaN handling.
Value
Dealing NumPy's linear algebra functions (np.li​nal​g.i​nv(),
Factorial np.fac​tor​ial(), np.comb()
with NaNs np.lin​alg.so​lve(), etc.) handle NaNs by raising LinAlg​‐
and
in Linear Error.
Combin​‐
Algebra
ations

Broadc​asting Gamma and np.gam​ma(), np.beta()


Beta
Broadc​asting is a powerful feature in NumPy that allows arrays of
Functions
different shapes to be combined in arithmetic operat​ions.
Sum, Mean, np.sum(), np.mean(), np.med​ian()
When operating on arrays of different shapes, NumPy automa​tically
Median
broadcasts the smaller array across the larger array so that they
have compatible shapes. Standard np.std(), np.var()
Deviation,
This eliminates the need for explicit looping over array elements,
Variance
making code more concise and efficient.
Matrix np.dot(), np.inn​er(), np.out​er(), np.cross()
Broadc​asting is partic​ularly useful for performing operations between
Operations
arrays of different dimensions or sizes without needing to reshape
them explic​itly. Eigenv​alues np.lin​alg.eig(), np.lin​alg.ei​gh(), np.lin​alg.ei​gvals()
and Eigenv​‐
ectors
Matrix np.lin​alg.svd(), np.lin​alg.qr(), np.lin​alg.ch​ole​sky()
Decomp​osi​‐
tions

Array Creation
numpy.a​ Create an array from a Python list or tuple.
rray()
Example arr = np.arr​ay([1, 2, 3])

numpy.z​ Create an array filled with zeros.


eros()
Example zeros_arr = np.zer​os((3, 3))

numpy.o​ Create an array filled with ones.


nes()
Example ones_arr = np.one​s((2, 2))

numpy.a​ Create an array with a range of values.


ra​nge()
Example range_arr = np.ara​nge(0, 10, 2) # array([0, 2, 4
)

numpy.l​‐ Create an array with evenly spaced values.


in​‐
space()

By Arshdeep Not published yet. Sponsored by Readable.com


cheatography.com/arshdeep/ Last updated 6th April, 2024. Measure your website readability!
Page 3 of 9. https://readable.com
Numpy Cheat Sheet
by Arshdeep via cheatography.com/201979/cs/42960/

Array Creation (cont) Statis​tical Functions

Example linspa​ce_arr = np.lin​spa​ce(0, 10, 5) mean 0., Computes


# array([ 2.5, 5.,the arithmetic
7.5, 10.mean along a specified axis.
]) median Computes the median along a specified axis.
numpy.e​‐ Create an identity matrix. average Computes the weighted average along a specified axis.
ye()
std Computes the standard deviation along a specified axis.
Example identi​ty_mat = np.eye(3)
var Computes the variance along a specified axis.
numpy.r​‐ Create an array with random values from a uniform distri​bution.
amin Finds the minimum value along a specified axis.
an​‐
amax Finds the maximum value along a specified axis.
dom.rand()
argmin Returns the indices of the minimum value along a
Example random_arr = np.ran​dom.ra​nd(2, 2)
specified axis.
numpy.r​‐ Create an array with random values from a standard normal distri​bution.
argmax Returns the indices of the maximum value along a
an​dom.ra​‐
specified axis.
ndn()
percentile Computes the q-th percentile of the data along a
Example random​_no​rma​l_arr = np.ran​dom.ra​ndn(2, 2)
specified axis.
numpy.r​‐ Create an array with random integers.
histogram Computes the histogram of a set of data.
an​dom.ra​‐
ndint()
Comparison with Python Lists
Example random​_in​t_arr = np.ran​dom.ra​ndi​nt(0, 10, size=(2, 2))
Perfor​‐ NumPy arrays are faster and more memory efficient
numpy.f​‐ Create an array filled with a specified value. mance compared to Python lists, especially for large datasets.
ull() This is because NumPy arrays are stored in
Example full_arr = np.ful​l((2, 2), 7) contiguous blocks of memory and have optimized

numpy.e​‐ Create an uninit​ialized array (values are not set, might be arbitr​ary). functions for mathem​atical operat​ions, whereas

mpty() Python lists are more flexible but slower due to their
dynamic nature.
Example empty_arr = np.emp​ty((2, 2))
Vectorized NumPy allows for vectorized operat​ions, which means
Operations you can perform operations on entire arrays without
Linear Algebra
the need for explicit looping. This leads to concise and
Matrix Multip​‐ np.dot() or @ operator for matrix multip​lic​ation.
efficient code compared to using loops with Python
lic​ation
lists.
Transpose np.tra​nsp​ose() or .T attribute for transp​osing a
Multid​ime​‐ NumPy supports multid​ime​nsional arrays, whereas
matrix.
nsional Python lists are limited to one-di​men​sional arrays or
Inverse np.lin​alg.inv() for calcul​ating the inverse of a matrix. Arrays nested lists, which can be less intuitive for handling
Determ​inant np.lin​alg.det() for computing the determ​inant of a multi-​dim​ens​ional data.
matrix.
Eigenv​alues np.lin​alg.eig() for computing eigenv​alues and
and Eigenv​‐ eigenv​ectors.
ectors
Matrix Functions like np.lin​alg.qr(), np.lin​alg.svd(), and
Decomp​osi​‐ np.lin​alg.ch​ole​sky() for various matrix decomp​osi​‐
tions tions.
Solving Linear np.lin​alg.so​lve() for solving systems of linear
Systems equations.
Vector​ization Leveraging NumPy's broadc​asting and array
operations for efficient linear algebra comput​ations.

By Arshdeep Not published yet. Sponsored by Readable.com


cheatography.com/arshdeep/ Last updated 6th April, 2024. Measure your website readability!
Page 4 of 9. https://readable.com
Numpy Cheat Sheet
by Arshdeep via cheatography.com/201979/cs/42960/

Comparison with Python Lists (cont) Masked Arrays

Broadc​‐ NumPy arrays support broadc​asting, which enables Why? Masked arrays in NumPy allow you to handle missing
asting operations between arrays of different shapes and or invalid data effici​ently.
sizes. In contrast, performing similar operations with What are Masked arrays are arrays with a companion boolean
Python lists would require explicit looping or list Masked mask array, where elements that are marked as "​mas​‐
compre​hen​sions. Arrays? ked​" are ignored during comput​ations.
Type NumPy arrays have a fixed data type, which leads to Creating You can create masked arrays using the numpy.m​‐
Stability better perfor​mance and memory effici​ency. Python lists Masked a.m​as​ked​_array function, specifying the data array and
can contain elements of different types, leading to Arrays the mask array.
potential type conversion overhead.
Masking Masking is the process of marking certain elements of
Rich Set of NumPy provides a wide range of mathem​atical and an array as invalid or missing. You can manually
Functions statis​tical functions optimized for arrays, whereas create masks or use functions like numpy.m​a.m​as​ked​‐
Python lists require manual implem​ent​ation or the use _where to create masks based on condit​ions.
of external libraries for similar functi​ona​lity.
Operations Operations involving masked arrays automa​tically
Memory NumPy arrays typically consume less memory with handle masked values by ignoring them in comput​‐
Usage compared to Python lists, especially for large datasets, Masked ations. This allows for easy handling of missing data
due to their fixed data type and efficient storage format. Arrays without explicitly removing or replacing them.
Indexing NumPy arrays offer more powerful and convenient Masked NumPy provides methods for masked arrays to
and Slicing indexing and slicing capabi​lities compared to Python Array perform various operations like calcul​ating statis​tics,
lists, making it easier to manipulate and access Methods manipu​lating data, and more. These methods are
specific elements or subarrays. similar to regular array methods but handle masked
Parallel NumPy operations can leverage parallel processing values approp​ria​tely.
Processing capabi​lities of modern CPUs through libraries like Intel Applic​‐ Masked arrays are useful in scenarios where datasets
MKL or OpenBLAS, resulting in signif​icant perfor​‐ ations contain missing or invalid data points. They are
mance gains for certain operations compared to commonly used in scientific computing, data analysis,
Python lists. and handling time series data where missing values
Intero​per​‐ NumPy arrays can be easily integrated with other are prevalent.
ability scientific computing libraries in Python ecosystem,
such as SciPy, Pandas, and Matplo​tlib, allowing
seamless data exchange and intero​per​abi​lity.

By Arshdeep Not published yet. Sponsored by Readable.com


cheatography.com/arshdeep/ Last updated 6th April, 2024. Measure your website readability!
Page 5 of 9. https://readable.com
Numpy Cheat Sheet
by Arshdeep via cheatography.com/201979/cs/42960/

Random Number Generation Filtering Arrays (cont)

np.ran​dom.rand Generates random numbers from a uniform Example arr = np.arr​ay([1, 2, 3, 4, 5])
distri​bution over [0, 1). filtered = arr[(arr > 2) & (arr < 5)]
np.ran​dom.randn Generates random numbers from a # Select elements between 2 and 5
standard normal distri​bution (mean 0, print(filtered)
standard deviation 1). # Output: [3 4]
np.ran​dom.ra​ndint Generates random integers from a specified Using NumPy also provides functions like np.where() and np.ext​‐
low (inclu​sive) to high (exclu​sive) range. Functions ract() for more complex filtering.
np.ran​dom.ra​ndo​m_s​‐ Generates random floats in the half-open Example arr = np.arr​ay([1, 2, 3, 4, 5])
ample or np.ran​‐ interval [0.0, 1.0). filtered = np.whe​re(arr % 2 == 0, arr, 0)
dom.random
np.ran​dom.choice Generates random samples from a given 1- # Replace odd elements with 0
D array or list. print(filtered)
np.ran​dom.sh​uffle Shuffles the elements of an array in place. # Output: [0 2 0 4 0]

np.ran​dom.pe​rmu​‐ Randomly permutes a sequence or returns


tation a permuted range. Array Iteration

np.ran​dom.seed Sets the random seed to ensure reprod​uci​‐ For Iterate over arrays using tradit​ional for loops. This is
bility of results. Loops useful for basic iteration but might not be the most
efficient method for large arrays.
Filtering Arrays nditer The nditer object allows iterating over arrays in a more

Filtering NumPy provides powerful tools for filtering arrays efficient and flexible way. It provides options to specify the

Arrays based on certain condit​ions. Filtering allows you to order of iteration, data type casting, and external loop

select elements from an array that meet specific handling.

criteria. Flat The flat attribute of NumPy arrays returns an iterator that

Syntax filter​ed_​array = array[​con​dition] Iteration iterates over all elements of the array as if it were a
flattened 1D array. This is useful for simple elemen​t-wise
Example import numpy as np
operat​ions.
arr = np.arr​ay([1, 2, 3, 4, 5])
Broadc​‐ When performing operations between arrays of different
filtered = arr[arr > 2]
asting shapes, NumPy automa​tically broadcasts the arrays to
# Select elements greater than 2
compatible shapes. Unders​tanding broadc​asting rules
print(filtered)
can help effici​ently iterate over arrays without explicit
# Output: [3 4 5]
loops.
Combining Conditions can be combined using logical operators
Conditions like & (and) and | (or).

By Arshdeep Not published yet. Sponsored by Readable.com


cheatography.com/arshdeep/ Last updated 6th April, 2024. Measure your website readability!
Page 6 of 9. https://readable.com
Numpy Cheat Sheet
by Arshdeep via cheatography.com/201979/cs/42960/

Array Iteration (cont) Array Reshaping (cont)

Vectorized Instead of explicit iteration, utilize NumPy's built-in ravel() Similar to flatten(), ravel() also flattens multi-​dim​ens​ional
Operations vectorized operations which operate on entire arrays arrays into a 1D array, but it returns a view of the original
rather than individual elements. This often leads to array whenever possible.
faster and more concise code. Example arr = np.arr​ay([[1, 2], [3, 4]])
raveled_arr = arr.ra​vel()
Array Reshaping
Explan​‐ This method can be more efficient in terms of memory
Array Reshaping arrays in NumPy allows you to change the ation usage than flatten().
Reshaping shape or dimensions of an existing array without
transp​‐ The transp​ose() method rearranges the dimensions of an
changing its data. This is useful for tasks like
ose() array. For 2D arrays, it effect​ively swaps rows and
converting a 1D array into a 2D array or vice versa, or
columns.
for preparing data for certain operations like matrix
Example arr = np.arr​ay([[1, 2], [3, 4]])
multip​lic​ation.
transposed_arr = arr.tr​ans​pose()
reshape() The reshape() function in NumPy allows you to change
the shape of an array to a specified shape. Explan​‐ This will transpose the 2x2 matrix, swapping rows and
ation columns.
For import numpy as np
example:
Sorting Arrays
arr = np.arr​ay([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.re​sha​pe((2, 3)) np.sor​‐ Returns a sorted copy of the array.
t(arr)
Explan​‐ This will reshape the array arr into a 2x3 matrix.
ation arr.sort() Sorts the array in-place.

resize() Similar to reshape(), resize() changes the shape of an np.arg​‐ Returns the indices that would sort the array.
array, but it also modifies the original array if necessary sor​t(arr)
to accomm​odate the new shape. np.lex​‐ Performs an indirect sort using a sequence of keys.
Example arr = np.arr​ay([[1, 2], [3, 4]]) sort()
resized_arr = np.res​ize​(arr, (3, 2)) np.sor​‐ Sorts the array of complex numbers based on the real
Explan​‐ If the new shape requires more elements than the t_c​omp​‐ part first, then the imaginary part.
ation original array has, resize() repeats the original array to lex​(arr)
fill in the new shape. np.par​‐ Rearranges the elements in such a way that the kth
flatten() The flatten() method collapses a multi-​dim​ens​ional tit​ion​‐ element will be in its correct position in the sorted array,
array into a 1D array by iterating over all elements in (arr, k) with all smaller elements to its left and all larger elements
row-major (C-style) order. to its right.

Example arr = np.arr​ay([[1, 2], [3, 4]]) np.arg​‐ Returns the indices that would partition the array.

flattened_arr = arr.fl​atten() par​tit​‐


ion​(arr,
Explan​‐ This will flatten the 2D array into a 1D array.
k)
ation

Array Indexing

Single Use square brackets [] to access individual elements of


Element an array by specifying the indices for each dimension. For
Access example, arr[0, 1] accesses the element at the first row
and second column of the array arr.

By Arshdeep Not published yet. Sponsored by Readable.com


cheatography.com/arshdeep/ Last updated 6th April, 2024. Measure your website readability!
Page 7 of 9. https://readable.com
Numpy Cheat Sheet
by Arshdeep via cheatography.com/201979/cs/42960/

Array Indexing (cont)

Negative Negative indices can be used to access elements from


Indexing the end of the array. For instance, arr[-1] accesses the
last element of the array arr.
Slice NumPy arrays support slicing similar to Python lists.
Indexing You can use the colon : operator to specify a range of
indices. For example, arr[1:3] retrieves elements from
index 1 to index 2 (inclu​sive) along the first axis.
Integer You can use arrays of integer indices to extract specific
Array elements from an array. For example, arr[[0, 2, 4]]
Indexing retrieves elements at indices 0, 2, and 4 along the first
axis.
Boolean You can use boolean arrays to filter elements from an
Array array based on a condition. For example, arr[arr > 0]
Indexing retrieves all elements of arr that are greater than zero.
(Boolean
Masking)
Fancy Fancy indexing allows you to select multiple elements
Indexing from an array using arrays of indices or boolean masks.
This method can be used to perform advanced selection
operations effici​ently.

By Arshdeep Not published yet. Sponsored by Readable.com


cheatography.com/arshdeep/ Last updated 6th April, 2024. Measure your website readability!
Page 8 of 9. https://readable.com

You might also like