Python ProgrammingPython Programming

Python NumPy

In this tutorial you will find solutions for your numeric and scientific computational problems using NumPy.

NumPy (short for Numerical Python) is an open source Python library for doing scientific computing with Python.

It gives an ability to create multidimensional array objects and perform faster mathematical operations. The library contains a long list of useful mathematical functions, including some functions for linear algebra and complex mathematical operations such as Fourier Transform (FT) and random number generator (RNG).

Most of the other libraries that we use in data analytics with Python, such as scikit-learn, SciPy and Pandas use some of NumPy's features.


Create NumPy Array

To create a NumPy array we need to pass list of element values inside a square bracket as an argument to the np.array() function.

A 3d array is a matrix of 2d array. A 3d array can also be called as a list of lists where every element is again a list of elements.

Example
import numpy as np
 
array1d = np.array([1, 2, 3, 4, 5, 6])
array2d = np.array([[1, 2, 3], [4, 5, 6]])
array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
 
print(array1d)
 
print("-" * 10)
print(array2d)
 
print("-" * 10)
print(array3d)
 
Output
[1 2 3 4 5 6]
----------
[[1 2 3]
 [4 5 6]]
----------
[[[ 1  2  3]
  [ 4  5  6]]
 
 [[ 7  8  9]
  [10 11 12]]]

The main data structure for multidimensional arrays in NumPy is the ndarray class. Basic Attributes of the ndarray Class as follow:

Attribute Description
Shape A tuple that specifies the number of elements for each dimension of the array.
Size The total number elements in the array.
Ndim Determines the dimension an array.
nbytes Number of bytes used to store the data.
dtype Determines the datatype of elements stored in array.

Data Types Supported by NumPy

The dtype method determines the datatype of elements stored in NumPy array. You can also explicitly define the data type using the dtype option as an argument of array function.

dtypeVariantsDescription
intint8, int16, int32, int64Integers
uintuint8, uint16, uint32, uint64Unsigned (nonnegative) integers
boolBoolBoolean (True or False)
code>floatfloat16, float32, float64, float128Floating-point numbers
complexcomplex64, complex128, complex256Complex-valued floating-point numbers

Example
import numpy as np
 
type1 = np.array([1, 2, 3, 4, 5, 6])
type2 = np.array([1.5, 2.5, 0.5, 6])
type3 = np.array(['a', 'b', 'c'])
type4 = np.array(["Canada", "Australia"], dtype='U5')
type5 = np.array([555, 666], dtype=float)
 
 
print(type1.dtype)
print(type2.dtype)
print(type3.dtype)
print(type4.dtype)
print(type5.dtype)
 
print(type4)
Output
int32
float64
<U1
<U5
float64
['Canad' 'Austr']

Shape of an array

The shape method determines the shape of NumPy array in form of (m, n) i.e (no. of rows) x (no. of columns).

Example
import numpy as np
 
array1d = np.array([1, 2, 3, 4, 5, 6])
array2d = np.array([[1, 2, 3], [4, 5, 6]])
array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
 
print(array1d.shape)
print(array2d.shape)
print(array3d.shape)
Output
(6,)
(2, 3)
(2, 2, 3)

Dimension of an array

The ndim method determines the dimension of NumPy array.

Example
import numpy as np
 
array1d = np.array([1, 2, 3, 4, 5, 6])
print(array1d.ndim)  # 1
 
array2d = np.array([[1, 2, 3], [4, 5, 6]])
print(array2d.ndim)  # 2
 
array3d = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
array3d = array3d.reshape(2, 3, 2)
print(array3d.ndim)  # 3

Resize an array

The resize() method modifies existing shape and array itself.

Example
import numpy as np
 
thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])
thearray.resize(4)
print(thearray)
 
print("-" * 10)
thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])
thearray.resize(2, 4)
print(thearray)
 
print("-" * 10)
thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])
thearray.resize(3, 3)
print(thearray)
Output
[1 2 3 4]
----------
[[1 2 3 4]
 [5 6 7 8]]
----------
[[1 2 3]
 [4 5 6]
 [7 8 0]]

Reshape an array

The reshape () method modifies existing shape but original array remains unchanged.

Example
import numpy as np
 
thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])
thearray = thearray.reshape(2, 4)
print(thearray)
 
print("-" * 10)
thearray = thearray.reshape(4, 2)
print(thearray)
 
print("-" * 10)
thearray = thearray.reshape(8, 1)
print(thearray)
Output
[[1 2 3 4]
 [5 6 7 8]]
----------
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
----------
[[1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]
 [8]]

Transform List or Tuple into NumPy array

The array() function can accept lists, tuples and other numpy.ndarray objects also to create new array object.

Example
import numpy as np
 
thelist = [1, 2, 3]
print(type(thelist))  # <class 'list'>
 
array1 = np.array(thelist)
print(type(array1))  # <class 'numpy.ndarray'>
 
 
thetuple = ((1, 2, 3))
print(type(thetuple))  # <class 'tuple'>
 
array2 = np.array(thetuple)
print(type(array2))  # <class 'numpy.ndarray'>
 
array3 = np.array([thetuple, thelist, array1])
print(array3)
Output
<class 'list'>
<class 'numpy.ndarray'>
<class 'tuple'>
<class 'numpy.ndarray'>
[[1 2 3]
 [1 2 3]
 [1 2 3]]

Special NumPy functions for generating arrays

Arrays with arange()

The arange() function creates an array with evenly spaced values between the specified start, end, and increment values.

General form: np.arange(Start, End, Increment)

Example
The reshape function is used to change its dimension:
import numpy as np
 
array1d = np.arange(5)  # 1 row and 5 columns
print(array1d)
 
array1d = np.arange(0, 12, 2)  # 1 row and 6 columns
print(array1d)
 
array2d = np.arange(0, 12, 2).reshape(2, 3)  # 2 rows 3 columns
print(array2d)
 
array3d = np.arange(9).reshape(3, 3)  # 3 rows and columns
print(array3d)
Output
[0 1 2 3 4]
[ 0  2  4  6  8 10]
[[ 0  2  4]
 [ 6  8 10]]
[[0 1 2]
 [3 4 5]
 [6 7 8]]

Arrays with linspace()

The linspace() function generates an array with evenly spaced values between specified start and end values, using a specified number of elements.

General form: np.linspace(Start, End, Number of elements)

Example
import numpy as np
 
array1d = np.linspace(1, 12, 2)
print(array1d)
 
array1d = np.linspace(1, 12, 4)
print(array1d)
 
array2d = np.linspace(1, 12, 12).reshape(4, 3)
print(array2d)
Output
[ 1. 12.]
[ 1.          4.66666667  8.33333333 12.        ]
[[ 1.  2.  3.]
 [ 4.  5.  6.]
 [ 7.  8.  9.]
 [10. 11. 12.]]

Arrays with logspace()

The logspace() function, generates an array with values that are logarithmically spaced between the given start and end values.

Example
import numpy as np
 
thearray = np.logspace(5, 10, num=10, base=10000000.0, dtype=float)
print(thearray)
Output
[1.00000000e+35 7.74263683e+38 5.99484250e+42 4.64158883e+46
 3.59381366e+50 2.78255940e+54 2.15443469e+58 1.66810054e+62
 1.29154967e+66 1.00000000e+70]

Zero Array

The zeros() function, generates an array with the specified dimensions and data type that is filled with zeros.

Example
import numpy as np
 
array1d = np.zeros(3)
print(array1d)
 
array2d = np.zeros((2, 4))
print(array2d)
Output
[0. 0. 0.]
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]]

One Array

The ones() function, generates an array with the specified dimensions and data type that is filled with ones.

Example
import numpy as np
 
array1d = np.ones(3)
print(array1d)
 
array2d = np.ones((2, 4))
print(array2d)
Output
[1. 1. 1.]
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]]

Full Array

The full() function, generates an array with the specified dimensions and data type that is filled with specified number.

Example
import numpy as np
 
array1d = np.full((3), 2)
print(array1d)
 
array2d = np.full((2, 4), 3)
print(array2d)
Output
[2 2 2]
[[3 3 3 3]
 [3 3 3 3]]

Eye Array

The eye() function, returns an array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.

Example
import numpy as np
 
array1 = np.eye(3, dtype=int)
print(array1)
 
array2 = np.eye(5, k=2)
print(array2)
Output
[[1 0 0]
 [0 1 0]
 [0 0 1]]
[[0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]]

Random Number Array

The np.random.rand method, generates an array with random numbers that are uniformly distributed between 0 and 1.

The np.random.randn method, generates an array with random numbers that are normally distributed between 0 and 1.

The np.random.randint method, generates an array with random numbers that are uniformly distributed between 0 and given integer.

Example
import numpy as np
 
print(np.random.rand(3, 2))  # Uniformly distributed values.
print(np.random.randn(3, 2))  # Normally distributed values.
 
# Uniformly distributed integers in a given range.
print(np.random.randint(2, size=10))
print(np.random.randint(5, size=(2, 4)))
Output
[[0.68428242 0.62467648]
 [0.28595395 0.96066372]
 [0.63394485 0.94036659]]
[[0.29458704 0.84015551]
 [0.42001253 0.89660667]
 [0.50442113 0.46681958]]
[0 1 1 0 0 0 0 1 0 0]
[[3 3 2 3]
 [2 1 2 0]]

Identity and Diagonal Array

The identity() function, generates square array with ones on the main diagonal whereas diag() function extract or construct diagonal array.

Example
import numpy as np
 
print(np.identity(3))
 
print(np.diag(np.arange(0, 8, 2)))
 
print(np.diag(np.diag(np.arange(9).reshape((3,3)))))
Output
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
[[0 0 0 0]
 [0 2 0 0]
 [0 0 4 0]
 [0 0 0 6]]
[[0 0 0]
 [0 4 0]
 [0 0 8]]

Operations on NumPy Arrays

Indexing

NumPy creates an appropriate scale index at the time of array creation. In order to access a single or multiple items of an array, we need to pass array of indexes in square brackets.

Indexing in two-dimensional array is represented by a pair of values, where the first value is the index of the row and the second is the index of the column.

Example
import numpy as np
 
array1d = np.array([1, 2, 3, 4, 5, 6])
print(array1d[0])   # Get first value
print(array1d[-1])  # Get last value
print(array1d[3])   # Get 4th value from first
print(array1d[-5])  # Get 5th value from last
 
# Get multiple values
print(array1d[[0, -1]])
 
print("-" * 10)
 
array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(array2d)
print("-" * 10)
 
print(array2d[0, 0])   # Get first row first col
print(array2d[0, 1])   # Get first row second col
print(array2d[0, 2])   # Get first row third col
 
print(array2d[0, 1])   # Get first row second col 
print(array2d[1, 1])   # Get second row second col
print(array2d[2, 1])   # Get third row second col
Output
1
6
4
2
[1 6]
----------
[[1 2 3]
 [4 5 6]
 [7 8 9]]
----------
1
2
3
2
5
8

Multidimensional Indexing

Indexing in a 3-Dimensional Array is based on syntax: array3d[L,M,N] where L is the first index, M is the row no. and N is the column no.

Example
import numpy as np
 
array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(array3d)
 
print(array3d[0, 0, 0])
print(array3d[0, 0, 1])
print(array3d[0, 0, 2])
 
print(array3d[0, 1, 0])
print(array3d[0, 1, 1])
print(array3d[0, 1, 2])
 
print(array3d[1, 0, 0])
print(array3d[1, 0, 1])
print(array3d[1, 0, 2])
 
print(array3d[1, 1, 0])
print(array3d[1, 1, 1])
print(array3d[1, 1, 2])
Output
[[[ 1  2  3]
  [ 4  5  6]]
 
 [[ 7  8  9]
  [10 11 12]]]
1
2
3
4
5
6
7
8
9
10
11
12

Single Dimensional Slicing

Slicing allows to extract portions of an array or select a subset of an existing array to generate new arrays. For slicing a sequence of numbers separated by colons (:) within square brackets.

Example
import numpy as np
 
array1d = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
 
print(array1d[4:])  # From index 4 to last index
 
print(array1d[:4])  # From index 0 to 4 index
 
print(array1d[4:7])  # From index 4(included) up to index 7(excluded)
 
print(array1d[:-1])  # Excluded last element
 
print(array1d[:-2])  # Up to second last index(negative index)
 
print(array1d[::-1])  # From last to first in reverse order(negative step)
 
print(array1d[::-2])  # All odd numbers in reversed order
 
print(array1d[-2::-2])  # All even numbers in reversed order
 
print(array1d[::])  # All elements
Output
[4 5 6 7 8 9]
[0 1 2 3]
[4 5 6]
[0 1 2 3 4 5 6 7 8]
[0 1 2 3 4 5 6 7]
[9 8 7 6 5 4 3 2 1 0]
[9 7 5 3 1]
[8 6 4 2 0]
[0 1 2 3 4 5 6 7 8 9]

Multidimensional Slicing

For a two-dimensional array, the same slicing syntax applies, but it is separately defined for the rows and columns.

Example
import numpy as np
 
array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
 
print("-" * 10)
print(array2d[:, 0:2])  # 2nd and 3rd col
 
print("-" * 10)
print(array2d[1:3, 0:3])  # 2nd and 3rd row
 
print("-" * 10)
print(array2d[-1::-1, -1::-1])  # Reverse an array
 
Output
----------
[[1 2]
 [4 5]
 [7 8]]
----------
[[4 5 6]
 [7 8 9]]
----------
[[9 8 7]
 [6 5 4]
 [3 2 1]]

Manipulating the Dimensions and the Shape of Arrays

Flips the order of the Axes

The transpose function transpose also exists as a method in ndarray and it permute the dimensions of an array. The fliplr (flip left-right) and flipud (flip up-down) functions perform operations that are similar to the transpose and the shape of the output array is the same as the input. The fliplr flip an array in the left/right direction. The flipud flip an array in the up/down direction. The rot90 Rotate an array by 90 degrees in the plane specified by axes and the rotation direction is from the first towards the second axis.

Example
import numpy as np
 
array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(array2d)
 
print("-" * 10)
 
# Permute the dimensions of an array.
arrayT = np.transpose(array2d)
print(arrayT)
 
print("-" * 10)
 
# Flip array in the left/right direction.
arrayFlr = np.fliplr(array2d)
print(arrayFlr)
 
print("-" * 10)
 
# Flip array in the up/down direction.
arrayFud = np.flipud(array2d)
print(arrayFud)
 
print("-" * 10)
 
# Rotate an array by 90 degrees in the plane specified by axes.
arrayRot90 = np.rot90(array2d)
print(arrayRot90)
 
Output
[[1 2 3]
 [4 5 6]
 [7 8 9]]
----------
[[1 4 7]
 [2 5 8]
 [3 6 9]]
----------
[[3 2 1]
 [6 5 4]
 [9 8 7]]
----------
[[7 8 9]
 [4 5 6]
 [1 2 3]]
----------
[[3 6 9]
 [2 5 8]
 [1 4 7]]

Joining and Stacking

NumPy uses the concept of stacking and provide a number of functions to perform: vertical stacking(row wise) using vstack(), horizontal stacking(column wise) using hstack() and depth wise stacking(along third axis) using dstack(). The concatenate() function creates a new array by appending arrays after each other, along a given axis. The append() function appends an element to an array and creates a new copy of the array.

Example
import numpy as np
 
array1 = np.array([[1, 2, 3], [4, 5, 6]])
array2 = np.array([[7, 8, 9], [10, 11, 12]])
 
# Stack arrays in sequence horizontally (column wise).
arrayH = np.hstack((array1, array2))
print(arrayH)
 
print("-" * 10)
 
# Stack arrays in sequence vertically (row wise).
arrayV = np.vstack((array1, array2))
print(arrayV)
 
print("-" * 10)
 
# Stack arrays in sequence depth wise (along third axis).
arrayD = np.dstack((array1, array2))
print(arrayD)
 
print("-" * 10)
 
# Appending arrays after each other, along a given axis.
arrayC = np.concatenate((array1, array2))
print(arrayC)
 
print("-" * 10)
 
# Append values to the end of an array.
arrayA = np.append(array1, array2, axis=0)
print(arrayA)
 
print("-" * 10)
arrayA = np.append(array1, array2, axis=1)
print(arrayA)
 
Output
[[ 1  2  3  7  8  9]
 [ 4  5  6 10 11 12]]
----------
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
----------
[[[ 1  7]
  [ 2  8]
  [ 3  9]]
 
 [[ 4 10]
  [ 5 11]
  [ 6 12]]]
----------
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
----------
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
----------
[[ 1  2  3  7  8  9]
 [ 4  5  6 10 11 12]]

Algebra with Arrays

Arithmetic Operations

The arithmetic operations with NumPy arrays perform element-wise operations, this means the operators are applied only between corresponding elements.

Example
import numpy as np
 
array1 = np.array([[1, 2, 3], [4, 5, 6]])
array2 = np.array([[7, 8, 9], [10, 11, 12]])
 
print(array1 + array2)
print("-" * 20)
 
print(array1 - array2)
print("-" * 20)
 
print(array1 * array2)
print("-" * 20)
 
print(array2 / array1)
print("-" * 40)
 
print(array1 ** array2)
print("-" * 40)
Output
[[ 8 10 12]
 [14 16 18]]
--------------------
[[-6 -6 -6]
 [-6 -6 -6]]
--------------------
[[ 7 16 27]
 [40 55 72]]
--------------------
[[7.  4.  3. ]
 [2.5 2.2 2. ]]
----------------------------------------
[[          1         256       19683]
 [    1048576    48828125 -2118184960]]
----------------------------------------

Scalar Arithmetic Operations

During scalar operations, the scalar value is applied to each element in the array.

Example
import numpy as np
 
array1 = np.array([[10, 20, 30], [40, 50, 60]])
 
print(array1 + 2)
print("-" * 20)
 
print(array1 - 5)
print("-" * 20)
 
print(array1 * 2)
print("-" * 20)
 
print(array1 / 5)
print("-" * 20)
 
print(array1 ** 2)
print("-" * 20)
Output
[[12 22 32]
 [42 52 62]]
--------------------
[[ 5 15 25]
 [35 45 55]]
--------------------
[[ 20  40  60]
 [ 80 100 120]]
--------------------
[[ 2.  4.  6.]
 [ 8. 10. 12.]]
--------------------
[[ 100  400  900]
 [1600 2500 3600]]
--------------------

Elementary Mathematical Functions

These mathematical functions takes a single array of any dimension as input and returns a new array of the same shape.


FunctionsDescription
np.cos(), np.sin(), np.tan()Trigonometric functions.
np.arccos(), np.arcsin(), np.arctan()Inverse trigonometric functions.
np.cosh(), np.sinh(), np.tanh()Hyperbolic trigonometric functions.
np.arccosh(), np.arcsinh(), np.arctanh()Inverse hyperbolic trigonometric unctions.
np.sqrt()Square root.
np.exp()Exponential.
np.log(), np.log2(), np.log10()Logarithms of base e, 2, and 10, respectively.

Example
import numpy as np
 
array1 = np.array([[10, 20, 30], [40, 50, 60]])
 
print(np.sin(array1))
print("-" * 40)
 
print(np.cos(array1))
print("-" * 40)
 
print(np.tan(array1))
print("-" * 40)
 
print(np.sqrt(array1))
print("-" * 40)
 
print(np.exp(array1))
print("-" * 40)
 
print(np.log10(array1))
print("-" * 40)
Output
[[-0.54402111  0.91294525 -0.98803162]
 [ 0.74511316 -0.26237485 -0.30481062]]
----------------------------------------
[[-0.83907153  0.40808206  0.15425145]
 [-0.66693806  0.96496603 -0.95241298]]
----------------------------------------
[[ 0.64836083  2.23716094 -6.4053312 ]
 [-1.11721493 -0.27190061  0.32004039]]
----------------------------------------
[[3.16227766 4.47213595 5.47722558]
 [6.32455532 7.07106781 7.74596669]]
----------------------------------------
[[2.20264658e+04 4.85165195e+08 1.06864746e+13]
 [2.35385267e+17 5.18470553e+21 1.14200739e+26]]
----------------------------------------
[[1.         1.30103    1.47712125]
 [1.60205999 1.69897    1.77815125]]
----------------------------------------

Element-wise Mathematical Operations


FunctionsDescription
np.add(), np.subtract(), np.multiply(), np.divide()Addition, subtraction, multiplication, and division of arguments(NumPy arrays) element-wise.
np.power()First array elements raised to powers from second array, element-wise.
np.remainder()Return element-wise remainder of division.
np.reciprocal()Return the reciprocal of the argument, element-wise.
np.sign(), np.abs()Return sign and the absolute value.
np.floor(), np.ceil()Return the floor, ceiling of the input, element-wise.
np.round()Round a number to a given precision in decimal digits (default 0 digits).

Example
import numpy as np
 
array1 = np.array([[10, 20, 30], [40, 50, 60]])
array2 = np.array([[2, 3, 4], [4, 6, 8]])
array3 = np.array([[-2, 3.5, -4], [4.05, -6, 8]])
 
print(np.add(array1, array2))
print("-" * 40)
 
print(np.power(array1, array2))
print("-" * 40)
 
print(np.remainder((array2), 5))
print("-" * 40)
 
print(np.reciprocal(array3))
print("-" * 40)
 
print(np.sign(array3))
print("-" * 40)
 
print(np.ceil(array3))
print("-" * 40)
 
print(np.round(array3))
print("-" * 40)
Output
[[12 23 34]
 [44 56 68]]
----------------------------------------
[[        100        8000      810000]
 [    2560000 -1554869184 -1686044672]]
----------------------------------------
[[2 3 4]
 [4 1 3]]
----------------------------------------
[[-0.5         0.28571429 -0.25      ]
 [ 0.24691358 -0.16666667  0.125     ]]
----------------------------------------
[[-1.  1. -1.]
 [ 1. -1.  1.]]
----------------------------------------
[[-2.  4. -4.]
 [ 5. -6.  8.]]
----------------------------------------
[[-2.  4. -4.]
 [ 4. -6.  8.]]
----------------------------------------

Aggregate and Statistical Functions


FunctionsDescription
np.mean()Compute the arithmetic mean along the specified axis.
np.std()Compute the standard deviation along the specified axis.
np.var()Compute the variance along the specified axis.
np.sum()Sum of array elements over a given axis.
np.prod()Return the product of array elements over a given axis.
np.cumsum()Return the cumulative sum of the elements along a given axis.
np.cumprod()Return the cumulative product of elements along a given axis.
np.min(), np.max()Return the minimum / maximum of an array or minimum along an axis.
np.argmin(), np.argmax()Returns the indices of the minimum / maximum values along an axis
np.all() Test whether all array elements along a given axis evaluate to True.
np.any()Test whether any array element along a given axis evaluates to True.

Example
import numpy as np
 
array1 = np.array([[10, 20, 30], [40, 50, 60]])
 
print("Mean: ", np.mean(array1))
 
print("Std: ", np.std(array1))
 
print("Var: ", np.var(array1))
 
print("Sum: ", np.sum(array1))
 
print("Prod: ", np.prod(array1))
 
Output
Mean:  35.0
Std:  17.07825127659933
Var:  291.6666666666667
Sum:  210
Prod:  720000000

Useful functions for Conditional and Logical Expressions

Updating using where()

The where() function is used to chooses values from arrays depending on the value of a specific condition.

Example
import numpy as np
 
before = np.array([[1, 2, 3], [4, 5, 6]])
 
# If element is less than 4, mul by 2 else by 3
after = np.where(before < 4, before * 2, before * 3)
 
print(after)
Output
[[ 2  4  6]
 [12 15 18]]

Updating using select()

The select() function return an array drawn from elements in choice list, depending on conditions.

Example
import numpy as np
 
before = np.array([[1, 2, 3], [4, 5, 6]])
 
# If element is less than 4, mul by 2 else by 3
after = np.select([before < 4, before], [before * 2, before * 3])
 
print(after)
Output
[[ 2  4  6]
 [12 15 18]]

Selection using choose()

Construct an array from an index array and a set of arrays to choose from.

Example
import numpy as np
 
before = np.array([[0, 1, 2], [2, 0, 1], [1, 2, 0]])
choices = [5, 10, 15]
 
after = np.choose(before, choices)
print(after)
 
print("-" * 10)
 
before = np.array([[0, 0, 0], [2, 2, 2], [1, 1, 1]])
choice1 = [5, 10, 15]
choice2 = [8, 16, 24]
choice3 = [9, 18, 27]
 
after = np.choose(before, (choice1, choice2, choice3))
print(after)
Output
[[ 5 10 15]
 [15  5 10]
 [10 15  5]]
----------
[[ 5 10 15]
 [ 9 18 27]
 [ 8 16 24]]

Logical Operations

logical_or computes the truth value of x1 OR x2 element-wise. logical_and computes the truth value of x1 AND x2 element-wise. logical_or computes the truth value of NOT x element-wise.

Example
import numpy as np
 
thearray = np.array([[10, 20, 30], [14, 24, 36]])
 
print(np.logical_or(thearray < 10, thearray > 15))
print("-" * 30)
 
print(np.logical_and(thearray < 10, thearray > 15))
print("-" * 30)
 
print(np.logical_not(thearray < 20))
print("-" * 30)
Output
[[False  True  True]
 [False  True  True]]
------------------------------
[[False False False]
 [False False False]]
------------------------------
[[False  True  True]
 [False  True  True]]
------------------------------