Cheat Sheet Numpy



Cheat

  • Python cheatsheet

Operators¶

NumPy for MATLAB users Help MATLAB/Octave Python Description doc help -i% browse with Info help Browse help interactively help help or doc doc help Help on using help.

Command

Description

*

multiplication operation: 2*3 returns 6

**

power operation: 2**3 returns 8

@

matrix multiplication:

returns

Numpy

Data Types¶

NumPy Cheat Sheets: Tips and Tricks „A Puzzle A Day to Learn, Code, and Play!“. Axis 1 Axis 0 → a.ndim = 2 „ axis 0 and axis 1“ → a.shape = (5, 4) „ five rows, four cols “ → a.size = 20 „5.4=20 elements “ 2D NumPy Array Axis 0 → a.ndim = 1 „ axis 0“ → a.shape = (5,) „ five rows “ → a.size = 5 „5 elements “ 1D NumPy Array Axis 1 Axis 0 → a.ndim = 3 „ axis 0 and axis 1“ → a.shape = (5, 4, 3) „5 rows, 4 cols, 3. Numpy python cheatsheet 1. 2 PythonForDataScience Cheat Sheet NumPy Basics Learn Python for Data Science Interactively at www.DataCamp.com NumPy DataCamp Learn Python for Data Science Interactively The NumPy library is the core library for scientific computing in Python.

Command

Description

l=[a1,a2,,an]

Constructs a list containing the objects (a1, a2,..., an). You can append to the list using l.append().The (ith) element of (l) can be accessed using l[i]

t=(a1,a2,,an)

Constructs a tuple containing the objects (a1, a2,..., an). The (ith) element of (t) can be accessed using t[i]

Built-In Functions¶

Command

Description

len(iterable)

len is a function that takes an iterable, such as a list, tuple or numpy array and returns the number of items in that object.For a numpy array, len returns the length of the outermost dimension

returns 5.

zip

Make an iterator that aggregates elements from each of the iterables.

returns [(1,4),(2,5),(3,6)]

Iterating¶

Datacamp numpy cheat sheet

Command

Description

forainiterable:

For loop used to perform a sequence of commands (denoted using tabs) for each element in an iterable object such as a list, tuple, or numpy array.An example code is

prints [1,4,9]

Numpy

Comparisons and Logical Operators¶

Command

Description

ifcondition:

Performs code if a condition is met (using tabs). For example

squares (x) if (x) is (5), otherwise cubes it.

User-Defined Functions¶

Command

Description

lambda

Used for create anonymous one line functions of the form:

The code after the lambda but before variables specifies the parameters. The code after the colon tells python what object to return.

def

The def command is used to create functions of more than one line:

The code immediately following def names the function, in this example g .The variables in the parenthesis are the parameters of the function. The remaining lines of the function are denoted by tab indents.The return statement specifies the object to be returned.

Numpy¶

Command

Description

np.array(object,dtype=None)

np.array constructs a numpy array from an object, such as a list or a list of lists.dtype allows you to specify the type of object the array is holding.You will generally note need to specify the dtype.Examples:

A[i1,i2,,in]

Access a the element in numpy array A in with index i1 in dimension 1, i2 in dimension 2, etc.Can use : to access a range of indices, where imin:imax represents all (i) such that (imin leq i < imax).Always returns an object of minimal dimension.For example,

A[:,2]

returns the 2nd column (counting from 0) of A as a 1 dimensional array and

A[0:2,:]

returns the 0th and 1st rows in a 2 dimensional array.

np.zeros(shape)

Constructs numpy array of shape shape. Here shape is an integer of sequence of integers. Such as 3, (1, 2), (2, 1), or (5, 5). Thus

np.zeros((5,5))

Constructs an (5times 5) array while

np.zeros(5,5)

will throw an error.

np.ones(shape)

Same as np.zeros but produces an array of ones

np.linspace(a,b,n)

Returns a numpy array with (n) linearly spaced points between (a) and (b). For example

np.linspace(1,2,10)

returns

np.eye(N)

Constructs the identity matrix of size (N). For example

np.eye(3)

returns the (3times 3) identity matrix:

[begin{split}left(begin{matrix}1&0&00&1&0 0&0&1end{matrix}right)end{split}]

np.diag(a)

np.diag has 2 uses. First if a is a 2 dimensional array then np.diag returns the principle diagonal of the matrix.Thus

np.diag([[1,3],[5,6]])

returns [1,6].

If (a) is a 1 dimensional array then np.diag constructs an array with $a$ as the principle diagonal. Thus,

np.diag([1,2])

returns

[begin{split}left(begin{matrix}1&00&2end{matrix}right)end{split}]

np.random.rand(d0,d1,,dn)

Constructs a numpy array of shape (d0,d1,,dn) filled with random numbers drawn from a uniform distribution between :math`(0, 1)`.For example, np.random.rand(2,3) returns

np.random.randn(d0,d1,,dn)

Same as np.random.rand(d0,d1,,dn) except that it draws from the standard normal distribution (mathcal N(0, 1))rather than the uniform distribution.

A.T

Reverses the dimensions of an array (transpose).For example,if (x = left(begin{matrix} 1& 23&4end{matrix}right)) then x.T returns (left(begin{matrix} 1& 32&4end{matrix}right))

np.hstack(tuple)

Take a sequence of arrays and stack them horizontally to make a single array. For example

returns [1,2,3,2,3,4] while

returns (left( begin{matrix} 1&22&3 3&4 end{matrix}right))

np.vstack(tuple)

Like np.hstack. Takes a sequence of arrays and stack them vertically to make a single array. For example

returns

np.amax(a,axis=None)

By default np.amax(a) finds the maximum of all elements in the array (a).Can specify maximization along a particular dimension with axis.If

a=np.array([[2,1],[3,4]])#createsa2dimarray

then

np.amax(a,axis=0)#maximizationalongrow(dim0)

returns array([3,4]) and

np.amax(a,axis=1)#maximizationalongcolumn(dim1)

returns array([2,4])

np.amin(a,axis=None)

Same as np.amax except returns minimum element.

np.argmax(a,axis=None)

Performs similar function to np.amax except returns index of maximal element.By default gives index of flattened array, otherwise can use axis to specify dimension.From the example for np.amax

returns array([1,1]) and

returns array([0,1])

np.argmin(a,axis=None)

Same as np.argmax except finds minimal index.

np.dot(a,b) or a.dot(b)

Returns an array equal to the dot product of (a) and (b).For this operation to work the innermost dimension of (a) must be equal to the outermost dimension of (b).If (a) is a ((3, 2)) array and (b) is a ((2)) array then np.dot(a,b) is valid.If (b) is a ((1, 2)) array then the operation will return an error.

numpy.linalg¶

Command

Description

np.linalg.inv(A)

For a 2-dimensional array (A). np.linalg.inv returns the inverse of (A).For example, for a ((2, 2)) array (A)

returns

np.linalg.eig(A)

Returns a 1-dimensional array with all the eigenvalues of $A$ as well as a 2-dimensional array with the eigenvectors as columns.For example,

eigvals,eigvecs=np.linalg.eig(A)

returns the eigenvalues in eigvals and the eigenvectors in eigvecs.eigvecs[:,i] is the eigenvector of (A) with eigenvalue of eigval[i].

np.linalg.solve(A,b)

Constructs array (x) such that A.dot(x) is equal to (b). Theoretically should give the same answer as

but numerically more stable.

Pandas¶

Command

Description

pd.Series()

Constructs a Pandas Series Object from some specified data and/or index

pd.DataFrame()

Constructs a Pandas DataFrame object from some specified data and/or index, column names etc.

or alternatively,

Plotting¶

Command

Description

plt.plot(x,y,s=None)

The plot command is included in matplotlib.pyplot.The plot command is used to plot (x) versus (y) where (x) and (y) are iterables of the same length.By default the plot command draws a line, using the (s) argument you can specify type of line and color.For example ‘-‘, ‘- -‘, ‘:’, ‘o’, ‘x’, and ‘-o’ reprent line, dashed line, dotted line, circles, x’s, and circle with line through it respectively.Color can be changed by appending ‘b’, ‘k’, ‘g’ or ‘r’, to get a blue, black, green or red plot respectively.For example,

plots the cosine function on the domain (0, 10) with a green line with circles at the points (x, v)

  • MATLAB–Python–Julia cheatsheet

Dependencies and Setup¶

In the Python code we assume that you have already run importnumpyasnp

In the Julia, we assume you are using v1.0.2 or later with Compat v1.3.0 or later and have run usingLinearAlgebra,Statistics,Compat

Creating Vectors¶

Operation

MATLAB

Python

Julia

Row vector: size (1, n)

Column vector: size (n, 1)

1d array: size (n, )

Not possible

or

Integers from j to n withstep size k

Linearly spaced vectorof k points

Creating Matrices¶

Operation

MATLAB

Python

Julia

Create a matrix

2 x 2 matrix of zeros

2 x 2 matrix of ones

2 x 2 identity matrix

Diagonal matrix

Uniform random numbers

Normal random numbers

Sparse Matrices

Tridiagonal Matrices

Manipulating Vectors and Matrices¶

Operation

MATLAB

Python

Julia

Transpose

Complex conjugate transpose(Adjoint)

Concatenate horizontally

or

or

Concatenate vertically

or

or

Reshape (to 5 rows, 2 columns)

Convert matrix to vector

Flip left/right

Flip up/down

Repeat matrix (3 times in therow dimension, 4 times in thecolumn dimension)

Preallocating/Similar

N/A similar type

Broadcast a function over acollection/matrix/vector

Functions broadcast directly

Functions broadcast directly

Numpy Cheat Sheet Dataquest

Accessing Vector/Matrix Elements¶

Operation

MATLAB

Python

Julia

Access one element

Access specific rows

Access specific columns

Remove a row

Diagonals of matrix

Get dimensions of matrix

Cheat Sheet Numpy

Mathematical Operations¶

Operation

MATLAB

Python

Julia

Dot product

Matrix multiplication

Inplace matrix multiplication

Not possible

Element-wise multiplication

Matrix to a power

Matrix to a power, elementwise

Inverse

or

or

Determinant

Eigenvalues and eigenvectors

Euclidean norm

Solve linear system(Ax=b) (when (A)is square)

Solve least squares problem(Ax=b) (when (A)is rectangular)

Datacamp Numpy Cheat Sheet

Sum / max / min¶

Operation

MATLAB

Python

Julia

Sum / max / min ofeach column

Sum / max / min of each row

Sum / max / min ofentire matrix

Cumulative sum / max / minby row

Cumulative sum / max / minby column

Programming¶

Operation

MATLAB

Python

Julia

Comment one line

Comment block

For loop

While loop

If

If / else

Print text and variable

Function: anonymous

Function

Tuples

Can use cells but watch performance

Named Tuples/Anonymous Structures

Closures

Inplace Modification

No consistent or simple syntaxto achieve this