logo

NumPy

NumPy

NumPy (Numerical Python) is a Python library used in scientific computing with other Python libraries. NumPy is used for working with arrays, NumPy arrays are faster to process than lists. Seaborn, matplotlib, and pandas libraries can be used with the NumPy library. Matplotlib library will be used in the tutorial below but you don't need to know it. However, if you are interested in Matplotlib library, you can always visit Matplotlib Tutorial. If you want to learn about the seaborn library, please visit the seaborn tutorial. If you want to learn about the pandas library, please visit the pandas tutorial. If you are interested in a specific topic, you can just jump into that topic. You can use your editor to test your code. NumPy 2.0.0 will be used for the tutorial below. If you want to try the examples online without installation, you can try Jupyter Notebook. It's easy and convenient. However, an old version of NumPy is installed, and new methods may not work.

Installing Numpy

You need to set up a virtual environment in Python. You need to install virtualenv. If you are using pip, run the command below:

pip install virtualenv

If you are using pip3, use pip3 instead of pip.

You need to create a virtual environment in your Python project folder. If you are using pip, run the command below:

python -m venv new_env

If you are using python3, use python3 instead of python. We named the virtual environment "new_env" but you can choose another name.

You can activate the environment:

source new_env/bin/activate

If you are using pip, run the command below:

pip install numpy

If you are using conda, run the command below:

conda install numpy

To check the version of NumPy library:

import numpy as np
print(np.__version__)

NumPy 2.0.0 will be used in the tutorial below. When you install with the command above, the latest version will be installed.

Matplotlib library will be used in the tutorial. You can install seaborn and pandas as well. If you are using pip, run the commands below:

pip install seaborn

pip install pandas

pip install matplotlib

If you are using conda, run the commands below:

conda install seaborn

conda install pandas

conda install -c conda-forge matplotlib

Import the seaborn and other libraries:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

NumPy Arrays, N-dimensional arrays

Creating arrays

Let's create a NumPy array:

arr = np.array([1, 2, 3])

The NumPy array above is one dimensional, you can also create a two-dimensional array:

arr = np.array([[1, 2, 3], [4, 5, 6]])

You can also import a CSV file:

np.genfromtxt('sample.csv', delimiter=',')

You can add more dimensions. You can also check the number of dimensions:

import numpy as np
print(arr.ndim)

You can create an array with the number of dimensions:

arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)

[[[[[1 2 3 4]]]]]

zeros()

You can create a NumPy array with zeros() function:

print(np.zeros([3, 2], dtype = np.int32))

[[0 0]
[0 0]
[0 0]]

The zeros() function returns a new array of given shape and types, filled with zeros like in the example above.

dtype property shows the data type. dtype can also be used to learn the data type of a variable:

x = np.ones([2, 2], dtype = np.int32)
print(x.dtype)

int32

If you want to change the data type, you can use astype property:

x = np.ones([2, 2], dtype = np.int32)
print("The first data type is ", x.dtype)
x = x.astype("float64")
print("The second data type is ", x.dtype)

The first data type is int32
The second data type is float64

ones()

You can create a NumPy array with np.ones() function:

print(np.ones([2, 2], dtype = np.int32))

[[1 1]
[1 1]]

np.ones() function returns a new array of given shape and type, filled with ones like in the example above.

full()

The np.full() returns a new array of given shape and types, filled with the specified value:

print(np.full([2, 2], 9))

[[9 9]
[9 9]]

Accessing elements

arr = np.array([1, 2, 3, 4])
print(arr[2])

The result is 3.

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print(arr[0, 1])

It represents the second element of the first array. The result is 2.

Please note that a two-dimensional array has two axes: axis 0 represents the column (values in the same column) and axis 1 represents the row (the values in the same row/array).

Slicing

You can slice arrays:

arr = np.array([1,2,3,4,5])
print(arr[1:3])

The result is [2,3]. You can also add a step:

arr = np.array([1,2,3,4,5])
print(arr[1:3:2])

The result is [2]

Logical Operators

You can also use logical operators:

arr = np.array([1, 3, 5, 7, 9, 11])
print(arr[arr>5])

[ 7 9 11]

arr = np.array([1, 3, 5, 7, 9, 11])
print(arr[(arr > 7) | (arr < 5)] )

[ 1 3 9 11]

Changing shape of an array

You can check the shape of an array:

print(arr.shape)

There are different ways to reshape an array. You can use reshape method to change the array. For example, you can change the dimension of an array:

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
new_arr = arr.reshape(3,3)
print(new_arr)

[[1 2 3]
[4 5 6]
[7 8 9]]

reshape method changes the dimensions of the first array.

You can also flatten an array:

arr = np.array([[1, 2], [3, 4]])
newarr = arr.reshape(-1)
print(newarr)

[1 2 3 4]

Operations with Numpy Arrays

There are different ways to perform an operation on arrays. For example, you can make an operation for all the elements in an array:

arr = np.array([1,3,5,7])
new_arr = arr + 2
print(new_arr)

[3 5 7 9]

Elements of arrays can also be added to each other:

test_1 = np.array([9, 9, 8, 1, 8])
test_2 = np.array([7, 10, 8, 3, 1])
test_3 = test_1 + test_2
print(test_3)

[16 19 16 4 9]

Universal Functions (ufunc)

A universal function (ufunc) is a function that operates on ndarrays. A ufunc takes a fixed number of specific inputs and produces a fixed number of specific outputs. ufuncs can also take optional arguments: where, dtype, and out (output array where the return value should be copied). There are currently more than 60 universal functions defined in numpy.

Math operations

You can use np.add(), np.subtract(), np.multiply(), np.divide(), np.power(), np.remainder(), np.divmod(), and the np.absolute() functions. You can use the same syntax for all functions. Let's see some of them:

add()

The np.add() function sums the content of two arrays, and returns the results in a new array.

import numpy as np
arr_1 = np.array([9, 9, 8, 1, 8])
arr_2 = np.array([7, 10, 8, 3, 1])
arr_3 = np.add(arr_1, arr_2)
print(arr_3)

[16 19 16 4 9]

power()

The first array elements are raised to powers from the second array elements in the np.power() method.

x = [1, 2, 3, 4]
y = [2, 4, 1, 3]
k = np.power(x,y)
print(k)

[ 1 16 3 64]

You need to calculate [12   24   31   43] for the result above.

remainder()

The np.remainder() returns the element-wise remainder of the division.

arr_1 = np.array([9, 6, 8, 7, 5])
arr_2 = np.array([7, 3, 2, 3, 4])
arr_3 = np.remainder(arr_1, arr_2)
print(arr_3)

[2 0 0 1 1]

You can get the same result with the mod() function.

divmod()

The np.divmod() returns the element-wise quotient and remainder simultaneously.

arr_1 = np.array([9, 6, 8, 7, 5])
arr_2 = np.array([7, 3, 2, 3, 4])
arr_3 = np.divmod(arr_1, arr_2)
print(arr_3)

(array([1, 2, 4, 2, 1]), array([2, 0, 0, 1, 1]))

absolute()

The np.abs() method calculates the absolute value element-wise.

arr_1 = np.array([-9, -6, -8, -7, -5])
new_arr = np.abs(arr_1)
print(new_arr)

[9 6 8 7 5]

Rounding decimals

You can use truncation, fix, round, floor, and ceil functions for rounding decimals.

trunc()

numpy.trunc() rounds to the nearest integer towards zero.

arr_1 = np.array([1.3, 2.5, 4.6])
new_arr = np.trunc(arr_1)
print(new_arr)

[1. 2. 4.]

You can get the same result with the numpy.fix() function.

floor()

The np.floor() function rounds off decimals to the nearest lower integer.

arr_1 = np.array([-1.3, -2.5, -4.6])
new_arr = np.floor(arr_1)
print(new_arr)

[-2. -3. -5.]

round()

The np.round() evenly rounds to the given number of decimals.

arr_1 = np.array([-1.34685, -2.54232, -4.64242])
new_arr = np.round(arr_1, 2)
print(new_arr)

[-1.35 -2.54 -4.64]

ceil()

The np.ceil() returns the ceiling of the input, element-wise:

arr_1 = np.array([-1.3, -2.5, -4.6])
new_arr = np.ceil(arr_1)
print(new_arr)

[-1. -2. -4.]

Logs

You can use log base 2 or 10 of the given array:

import numpy as np
arr = np.arange(1, 8)
print(np.log2(arr))

*numpy.arange returns evenly spaced values within a given interval.

[0. 1. 1.5849625 2. 2.32192809 2.5849625 2.80735492]

log base 10:

import numpy as np
arr = np.array([10, 100, 1000])
print(np.log10(arr))

[1. 2. 3.]

The natural logarithm is the inverse of the exponential function.

Summation

sum()

The np.sum() calculates the sum of array elements over a given axis:

arr_1 = np.array([3, 2, 4])
new_arr = np.sum(arr_1)
print(new_arr)

The result is 9. Please note that np.sum() and np.add() functions are different.

You can also sum over an axis:

arr_1 = np.array([3, 2, 4])
arr_2 = np.array([3, 2, 4])
new_arr = np.sum([arr_1, arr_2], axis=1)
print(new_arr)

[9 9]

cumsum()

The np.cumsum() returns the cumulative sum of the elements along a given axis.

arr = np.array([2, 4, 6])
new_arr = np.cumsum(arr)
print(new_arr)


[ 2 6 12]

Products

prod()

The np.prod() returns the product of array elements over a given axis.

arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([1, 2, 3, 4])
x = np.prod([arr1, arr2])
print(x)

The result (1 * 2 * 3 * 4 * 1 * 2 * 3 * 4) is 576.

Differences

diff()

The np.diff() method calculates the n-th discrete difference along the given axis.

arr1 = np.array([1, 2, 3, 4])
x = np.diff(arr1)
print(x)

The result is [1 1 1] because 2-1=1, 3-2=1, 4-3=1.

Finding Lowest Common Multiple (LCM) and Greatest Common Denominator (GCD)

Finding Lowest Common Multiple (LCM)

The np.lcm() returns the lowest common multiple of the array:

arr = np.array([4, 5, 20])
x = np.lcm.reduce(arr)
print(x)

The result is 20.

Greatest Common Denominator (GCD)

The numpy.gcd() returns the greatest common divisor of two elements:

arr = np.array([4, 8, 12])
x = np.gcd.reduce(arr)
print(x)

The result is 4.

Set operations

A set in mathematics is a collection of unique elements. You can use unique method to find unique elements from an array:

arr = np.array([4, 8, 12, 4, 6, 8])
x = np.unique(arr)
print(x)

[ 4 6 8 12]

The set arrays can have only one dimension.

Finding union union1d()

numpy.union1d() finds the union of two arrays.

arr = np.array([4, 8, 12])
arr2 = np.array([4,9,15])
x = np.union1d(arr, arr2)
print(x)

[ 4 8 9 12 15]

np.union1d joins the two arrays. As it's a set array, common elements don't repeat.

Finding intersection intersect1d()

np.intersect1d() finds the intersection of two arrays.

arr = np.array([4, 8, 12])
arr2 = np.array([4,9,15])
x = np.intersect1d(arr, arr2)
print(x)

[4]

Finding Difference setdiff1d()

np.setdiff1d() finds the set difference of two arrays. It returns the unique values in the first array that are not in the second array.

arr = np.array([4, 8, 12])
arr2 = np.array([4,9,15])
x = np.setdiff1d(arr, arr2)
print(x)

[ 8 12]

Finding Symmetric Difference setxor1d()

np.setxor1d() finds the set exclusive-or of two arrays.

arr = np.array([4, 8, 12])
arr2 = np.array([4,9,15])
x = np.setxor1d(arr, arr2)
print(x)

[ 8 9 12 15]

setxor1d returns the unique values of two arrays.

Please note that functions always return sorted, unique values.

Create your own ufunc

frompyfunc()

The numpy.frompyfunc helps you create your ufunc. It takes 3 arguments: the name of the function, the number of input array(s) and the number of output array(s).

def subt(x, y):
  return x-y
subt = np.frompyfunc(subt, 2, 1)
print(subt([8, 7, 6], [3, 2, 1]))

[5 5 5]

Statistics with NumPy

You can use NumPy to analyze the data. You can find examples of the numpy mean, numpy median, numpy sort, numpy percentile, and numpy standard deviation methods below. They are used in statistics and machine learning.

mean()

The np.mean() computes the arithmetic mean along the specified axis.

x = np.array([8, 7, 6, 3, 2, 1])
y = np.mean(x)
print(y)

The result is 4.5

median()

The np.median() computes the median along the specified axis.

x = np.array([8, 7, 6, 3, 2, 1])
y = np.median(x)
print(y)

The result is 4.5

While the np.mean shows the average value of the elements in an array, the np.median shows the middle value. median is the data value in the middle of the set (when the array is sorted). If the total number of the array is even, average of the 2 data values in the middle is the median.

sort()

We can use the np.sort() function to sort a Numpy array:

x = np.array([12, 15, 59, 9, 2, 10])
print(np.sort(x))

[ 2 9 10 12 15 59]

percentile

The np.percentile computes the q-th percentile of the data along the specified axis. It returns the q-th percentile(s) of the array elements.

x = np.array([1, 3, 5, 7, 9])
y = np.percentile(x, 25)
print(y)

The result is 3.0

standard deviation

np.std() computes the standard deviation — a measure of the spread or dispersion of a distribution — for the elements in an array along the specified axis.

x = np.array([1, 3, 5, 7, 9])
y = np.std(x)
print(y)

The result is 2.8284271247461903

Histogram

You can use a histogram with NumPy. You will need matplotlib:

import numpy as np
from matplotlib import pyplot as plt

number_of_visitors = np.array([15, 25, 30, 54, 43, 35, 63, 37, 18, 28, 30, 35])
plt.hist(number_of_visitors)
plt.show()

numpy with histogram example

Linear Algebra with NumPy (numpy.linalg)

dot()

The dot is the product of two arrays:

a = np.array([[ 0, 1],
[-2, -3]])
b = np.array([[ 2, 4],
[5, 2]])
x = np.dot(a,b)
print(x)

[[ 5 2]
[-19 -14]]

To find the result above:
[[0*2 + 1*5     0*4 + 1*2]
[-2*2 + -3*5     -2*4 + -3*2]]

vdot()

The vdot() returns the dot product of two vectors:

a = np.array([ 0, 1])
b = np.array([2,3])
x = np.vdot(a, b)
print(x)

The result is (0*2 + 1*3) 3.

inner()

The inner() calculates the inner product of two arrays.

a = np.array([ 0, 1, 2, 3])
b = np.array([4, 5, 6, 7])
x = np.inner(a, b)
print(x)

a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3]

The result is 38.

outer()

The outer computes the outer product of two vectors:

a = np.array([ 0, 1, 2])
b = np.array([4, 5, 6])
x = np.outer(a, b)
print(x)

[[ 0 0 0]
[ 4 5 6]
[ 8 10 12]]

You need to make the following multiplications for the result above: [0*4   0*5   0*6] [1*4   1*5   1*6] [2*4   2*5   2*6]

matmul

The matmul() calculates the matrix product of two arrays:

a = np.array([[ 0, 1, 3],
[-2, -3, 2],
[1, 2, 1]])
b = np.array([[ 2, 4],
[5, 2],
[1,2]])
x = np.matmul(a,b)
print(x)

[[8 8]
[-17 -10]
[ 13 10]]

einsum

The np.einsum() evaluates the Einstein summation convention on the operands:

x = np.array([1,2,3])
y = np.array([2,4,6])
z = np.einsum("a, b", x, y)
print(z)

You need to multiply all the elements of the first array with the elements of the second array [[2*1 2*2 2*3] [4*1 4*2 4*3] [6*1 6*2 6*3]].

[[ 2 4 6]
[ 4 8 12]
[ 6 12 18]]

The np.einsum method can give the same result with matmul, if it has more than one dimension:

x = np.array([[1,2],
[3,4]])
y = np.array([[2,4],
[1,3]])
z = np.einsum('ij,jk->ik', x, y)
print(z)

[[ 4 10]
[10 24]]

Eigenvalues and eigenvectors

linalg.eig

The np.linalg.eig computes the eigenvalues and right eigenvectors of a square matrix.

a = np.array([[ 0, 1],
[ 2, 3]])
eigenvalues, eigenvectors = np.linalg.eig(a)
print("eigenvalues are: ", eigenvalues)
print("eigenvectors are: ", eigenvectors)

eigenvalues are: [-0.56155281 3.56155281]
eigenvectors are: [[-0.87192821 -0.27032301]
[ 0.48963374 -0.96276969]]

linalg.eigvals

np.linalg.eigvals computes the eigenvalues of a general matrix:

a = np.array([[ 0, 1],
[ 2, 3]])
eigenvalues= np.linalg.eigvals(a)
print("eigenvalues are: ", eigenvalues)

eigenvalues are: [-0.56155281 3.56155281]

linalg.eigh

The np.linalg.eigh returns the eigenvalues and eigenvectors of a complex Hermitian (conjugate symmetric) or a real symmetric matrix.

f = np.array([[ 0, 1+2j],
[1-2j, 3]])
x, y = np.linalg.eigh(f)
print("eigenvalues are ", x)
print("eigenvectors are ", y)

eigenvalues are [-1.1925824 4.1925824]
eigenvectors are [[-0.88235084-0.j -0.47059217+0.j ]
[ 0.21045522-0.42091043j -0.39459929+0.78919858j]]

eigvalsh

The np.linalg.eigvalsh computes the eigenvalues of a complex Hermitian or real symmetric matrix. It's similar to np.linalg.eigh but the eigenvectors are not computed.

f = np.array([[ 0, 1+2j],
[1-2j, 3]])
eigenvalues= np.linalg.eigvalsh(f)
print("eigenvalues are: ", eigenvalues)

eigenvalues are: [-1.1925824 4.1925824]

linalg.det

The np.linalg.det() computes the determinant of an array.

a = np.array([[6, 5],
[4, 3]])
det = np.linalg.det(a)
print(det)

In order to calculate the determinant, (6*3) - (5*4). The result is -1.999999999999999.

linalg.trace

The np.linalg.trace method returns the sum along the diagonals of the array.

from numpy import linalg
a = np.array([[1, 5, 3], [4, 2, 1], [3, 6, 2]])
trace = np.linalg.trace(a)
print(trace)

The result is (1+2+2) 5.

The np.linalg.trace() method doesn't work in older versions of NumPy, you can get AttributeError: module 'numpy.linalg' has no attribute 'trace'. You can alternatively use the trace() method for the same result:

import numpy as np
a = np.array([[1, 2, 3], [3, 5, 6], [4, 3,2]])
trace = np.trace(a)

The result is 8.

linalg.diagonal

The np.linalg.diagonal returns specified diagonals of a matrix:

a = np.array([[1, 5], [4, 2]])
diag = np.linalg.diagonal(a)
print(diag)

[1 2]

The np.linalg.diagonal() method doesn't work in older versions of NumPy, you can get an AttributeError: module 'numpy.linalg' has no attribute 'diagonal'. You can alternatively use the diagonal() method for the same result:

a = np.array([[1, 5], [4, 2]])
diag = np.diagonal(a)
print(diag)

[1 2]

linalg.matrix_transpose

The np.linalg.matrix_transpose() function returns the transpose of a matrix or a stack of matrices passed as input.

a = np.array([[1, 5], [4, 2]])
transpose = np.linalg.matrix_transpose(a)
print(transpose)

[[1 4]
[5 2]]

The np.linalg.matrix_transpose method doesn't work in older versions of NumPy, you can get an AttributeError: module 'numpy.linalg' has no attribute 'matrix_transpose'. You can alternatively use the transpose() method for the same result:

import numpy as np
a = np.array([[1, 5], [4, 2]])
transpose = np.transpose(a)

linalg.solve

The np.linalg.solve() solves a linear matrix equation, or system of linear scalar equations.

a = np.array([[2, 2], [4, 2]])
b = np.array([6,12])
solution = np.linalg.solve(a,b)
print(solution)

[3. 0.]

2x + 2y = 6 and 4x + 2y = 12

linalg.inv

The np.linalg.inv() computes the inverse of a matrix:

a = np.array([[2, 2], [4, 2]])
inverse = np.linalg.inv(a)
print(inverse)

[[-0.5 0.5]
[ 1. -0.5]]

If the determinant of the matrix is 0, you will get the "Singular matrix" error. It means your matrix is non-invertible. You can alternatively use linalg.pinv.

linalg.pinv

If your matrix is not invertible (see linalg.inv), you can use numpy.linalg.pinv. linalg.pinv computes the (Moore-Penrose) pseudo-inverse of a matrix:

x = [[2,2], [2,2]]
print(np.linalg.pinv(x))

[[0.125 0.125]
[0.125 0.125]]

It calculates the inverse of a matrix using its singular-value decomposition (SVD) and including all large singular values.

NumPy Random (numpy.random)

If you need random sampling, you can use numpy.random module.

randint

The randint method generates an integer between 0 and the specified number:

from numpy import random
x = random.randint(50)
print(x)

The result is 5. The randint method generates an integer between 0-50 in the example above.

Generating a random array

randint

The randint generates a random array with the specified size:

from numpy import random
x=random.randint(100, size=(3))
print(x)

[28 45 69]

The size parameter specifies the shape of an array.

rand

The rand can generate a random array with floats. size parameter is used to specify the shape of the returned array.

from numpy import random
x = random.rand(2, 3)
print(x)

[[0.02119792 0.38030721 0.92025197]
[0.19259276 0.32973657 0.9148083 ]]

The example above generated a random array with 2 rows and 3 columns. The rand method generates arrays with floats.

choice

The choice method chooses an element from an array:

from numpy import random
x = random.choice([3, 5, 7, 9])
print(x)

The result is 7.

You can specify the shape of the array with the size parameter:

from numpy import random
x = random.choice([3, 5, 7, 9], size=(2,2))
print(x)

[[7 5]
[3 7]]

Data Distribution

You can use the random module for data distribution. It is used in machine learning and statistics.

Permutation and Shuffle

shuffle and permutation methods can be used. The shuffle method randomly shuffles elements of an array:

from numpy import random
arr = np.array([2, 4, 6])
random.shuffle(arr)
print(arr)

[4 2 6]

The permutation method randomly permutes a sequence, or returns a permuted range.

from numpy import random
x = np.array([2, 4, 6])
random.permutation(x)
print(x)

[4 2 6]

Normal

The normal() method draws random samples from a normal (Gaussian) distribution. The data is symmetrically distributed around the mean.

from numpy import random
x = random.normal(size=(2,2))
print(x)

[[ 0.55432657 -0.80872333]
[-0.84319299 -0.53887013]]

You can also use normal to create a random array with a size, mean and standard deviation:

from numpy import random
x = random.normal(loc=5, scale=2, size=(2, 3))
print(x)

[[9.66770454 4.29139593 3.98125015]
[3.19591534 5.3704507 5.30760289]]

The loc parameter refers to mean (5 in the example), the scale parameter (2 in the example) refers to standard deviation, and the size (2,3) shows the shape of the array in the example above.

If you want to show the visualization of your distribution, you can use the seaborn library.

Binomial

The binomial method draws samples from a binomial distribution. The binomial distribution is a discrete probability distribution, and it can have only two possible results.

from numpy import random
x = random.binomial(n=3, p=0.5, size=5)
print(x)

[0 2 2 2 1]

The parameter n, which denotes the number of independent trials in the distribution, should be greater than or equal to 0. Floats are accepted, but they will be truncated to integers. p is the parameter of the distribution between 0 and 1. size parameter shows the shape of the array.

Poisson

The poisson distribution is a discrete probability distribution. It has 2 parameters: lam and size. The lam is the expected number of events occurring in a fixed-time interval. size is the output shape.

from numpy import random
x = random.poisson(lam=2, size=5)
print(x)

See the difference between poisson distribution and exponential distribution.

[0 0 4 2 1]

Uniform

All events have an equal chance of occurring in a uniform distribution. The uniform method draws samples from a uniform distribution. a parameter represents the lower bound and the default value is 0. b parameter represents the upper bound and the default value is 1. The size is the shape of the returned array:

from numpy import random
x = random.uniform(size=(2, 2))
print(x)

[[0.82522303 0.96689785]
[0.97534626 0.33729442]]

Logistic

The logistic method helps to draw samples from a logistic distribution. logistic distribution is used to model growth.

The logistic method has 3 parameters: loc, scale, and size. The loc represents the mean of the array, and the default value is 0. The scale represents the standard deviation, the default value is 1.

from numpy import random
x = random.logistic(loc=3, scale=2, size=(2, 2))
print(x)

[[ 2.17125771 5.84361473]
[13.19869728 3.51022713]]

Multinomial

The multinomial is used to draw samples from the multinomial distribution. The multinomial distribution is similar to the binomial distribution, but it may have p possible outcomes. It has 3 parameters: n, pvals, size. n represents the number of possible outcomes. pvals represents the list of possibilities of outcomes.

from numpy import random
x = random.multinomial(n=3, pvals=[1/3, 1/3, 1/3])
print(x)

[0 2 1]

Exponential

The exponential is used to draw samples from an exponential distribution. It has 2 parameters: scale and size. The scale represents the inverse rate, the default value is 1.

from numpy import random
x = random.exponential(scale=5, size=(2, 2))
print(x)

[[ 1.8336431 4.72914034]
[ 1.41002221 14.83021248]]

Exponential distribution deals with the time between events, poisson distribution deals with the number of events taking place in a given (time) period. While exponential distribution is a continuous probability distribution, poisson distribution is a discrete probability distribution.

Chi-square

The chi-square distribution represents the probability distribution of several independent squared random variables. The numpy chisquare method draws samples from a chi-square distribution. It has 2 parameters: df and size. df is the number of degrees of freedom, it represents the independent random variables.

from numpy import random
x = random.chisquare(df=2, size=(2, 3))
print(x)

[[0.14248928 1.72224754 0.6367974 ]
[3.29349291 3.20701167 4.95018512]]