NumPy Methods
NumPy Methods
array([[ 1, 2],
[ 3, 41]])
>>> np.ravel(arr)
array([ 1, 2, 3, 41])
array([ 1, 3, 2, 41])
Use List to Change the Positions of Rows or Columns in
a NumPy Array
If you want to change the positions of rows or columns in a NumPy array, simply use a
list to specify the new positions as shown below.
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
array([[4, 5, 6],
[7, 8, 9],
[1, 2, 3]])
Difference Between NumPy’s All and Any Methods
If you want to get the row whose ALL values satisfy a certain condition, use NumPy’s
all method.
array([[1, 2, 1]])
To get the row whose AT LEAST one value satisfies a certain condition, use NumPy’s
any method.
array([[1, 2, 1],
[2, 2, 5]])
Double numpy.argsort: Get Rank of Values in an Array
If you want to get the index of the sorted list for the original list, apply
numpy.argsort() twice.
array([1, 0, 3, 4, 2])
2
np.where: Replace Elements of a NumPy Array Based
on a Condition
If you want to replace elements of a NumPy array based on a condition, use
numpy.where.
Sometimes you might want to use latex to write math. You can turn a NumPy array into
latex using array-to-latex.
\begin{bmatrix}
1.00 & 2.00 & 3.00\\
4.00 & 5.00 & 6.00
\end{bmatrix}
I copied and pasted the output of array-to-latex to the Markdown cell of Jupyter
Notebook, and below is the output.
Link to array-to-latex.
NumPy Comparison Operators
If you want to get elements of a NumPy array that are greater, smaller, or equal to a value
or an array, simply use comparison operators such as <, <=, >, >=, ==.
>>> a < 2
>>> a < b
array([1])
NumPy.linspace: Get Evenly Spaced Numbers Over a
Specific Interval
If you want to get evenly spaced numbers over a specific interval, use
numpy.linspace(start, stop, num). The code below shows a use case of the
numpy.linspace method.
>>> y = np.arange(10)
>>> plt.plot(x, y)
>>> plt.show()
NumPy.testing.assert_almost_equal: Check if Two
Arrays Are Equal up to a Certain Precision
Sometimes, you might only want to check if two arrays are equal up to a certain precision.
If so, use numpy.testing.assert_almost_equal.
AssertionError:
Arrays are not equal