PL03-Topic02, NumPy
Back to the previous page |page management
List of posts to read before reading this article
Contents
- Installation
- Data Load/Save
- The numpy array object
- Creating arrays
- Indexing and slicing
- Reshaping and resizeing
- Delete
- Vectorized expreesions
- Matrix and vector operations
- Generating random numbers
- Clipping
Installation
For linux
$ pip install numpy
$ pip install -U numpy
$ pip list | grep numpy
For windows
pip install numpy
pip install -U numpy
pip list | find "numpy"
Data Load/Save
import numpy as np
np.loadtxt('file_path', dtype='string')
import numpy as np
x = y = z = np.arange(0.0,5.0,1.0)
np.savetxt('test.out', x, delimiter=',') # X is an array
np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays
np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation
The numpy array object
>>> import numpy as np
>>> data = np.array([[1, 2],[3, 4],[5, 6]])
>>> type(data)
numpy.ndarray
>>> data
array([[1, 2],
[3, 4],
[5, 6]])
>>> data.ndim
2
>>> data.shape
(3, 2)
>>> data.size
6
>>> data.dtype
dtype('int32')
>>> data.nbytes
24
Data types
>>> import numpy as np
>>> np.array([1,2,3],dtype=np.int)
array([1, 2, 3])
>>> np.array([1,2,3],dtype=np.float)
array([1., 2., 3.])
>>> np.array([1,2,3],dtype=np.complex)
array([1.+0.j, 2.+0.j, 3.+0.j])
>>> data = np.array([1,2,3], dtype=np.float)
>>> data
array([1., 2., 3.])
>>> data.dtype
dtype('float64')
>>> data = np.array(data, dtype=np.int)
>>> data.dtype
dtype('int32')
>>> data
array([1, 2, 3])
>>> data = np.array([1, 2, 3], dtype=np.float)
>>> data
array([1., 2., 3.])
>>> data.astype(np.int)
array([1, 2, 3])
>>> d1 = np.array([1, 2, 3], dtype=float)
>>> d2 = np.array([1, 2, 3], dtype=complex)
>>> d1 + d2
array([2.+0.j, 4.+0.j, 6.+0.j])
>>> (d1 + d2).dtype
dtype('complex128')
>>> np.sqrt(np.array([-1, 0, 1]))
array([nan, 0., 1.])
>>> np.sqrt(np.array([-1, 0, 1], dtype=complex))
array([0.+1.j, 0.+0.j, 1.+0.j])
Real and imaginary parts
>>> import numpy as np
>>> data = np.array([1, 2, 3], dtype=complex)
>>> data
array([1.+0.j, 2.+0.j, 3.+0.j])
>>> data.real
array([1., 2., 3.])
>>> data.imag
array([0., 0., 0.])
Creating arrays
Arrays created from lists and other array-like objects
>>> import numpy as np
>>> np.array([1, 2, 3, 4])
array([1, 2, 3, 4])
>>> data = np.array([1, 2, 3], dtype=complex)
>>> data.ndim
1
>>> data.shape
(3,)
>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])
>>> data.ndim
1
>>> data.shape
(3,)
Arrays filled with constant values
zeros & ones
>>> import numpy as np
>>> np.zeros((2, 3))
array([[0., 0., 0.],
[0., 0., 0.]])
>>> np.ones(4)
array([1., 1., 1., 1.])
>>> data = np.ones(4)
>>> data.dtype
dtype('float64')
>>> data = np.ones(4, dtype=np.int64)
>>> data.dtype
dtype('int64')
full = empty + fill
>>> import numpy as np
>>> x1 = 5.4 * np.ones(10)
>>> x1
array([5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4])
>>> x2 = np.full(10, 5.4)
>>> x2
array([5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4, 5.4])
>>> x1 = np.empty(5)
>>> x1.fill(3.0)
>>> x1
array([3., 3., 3., 3., 3.])
# empty + fill = full
>>> x2 = np.full(5, 3.0)
>>> x2
array([3., 3., 3., 3., 3.])
SUPPLEMENT
Except for zeros, ones, leaving things are not defined such as twos, to be able to span another space with 'arbitary number * np.ones'
repeat
>>> import numpy as np
>>> np.repeat(0,0)
array([], dtype=int32)
>>> np.repeat(0,1)
array([0])
>>> np.repeat(0,2)
array([0, 0])
>>> np.repeat(0,3)
array([0, 0, 0])
>>> np.repeat(1,0)
array([], dtype=int32)
>>> np.repeat(1,1)
array([1])
>>> np.repeat(1,2)
array([1, 1])
>>> np.repeat(1,3)
array([1, 1, 1])
>>> np.repeat(5,0)
array([], dtype=int32)
>>> np.repeat(5,1)
array([5])
>>> np.repeat(5,2)
array([5, 5])
>>> np.repeat(5,3)
array([5, 5, 5])
Arrays filled with incremental sequences
>>> import numpy as np
>>> np.arange(0.0, 10, 1)
array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
>>> np.linspace(0, 10, 11)
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
SUPPLEMENT
np.arange(~, ~, i) : i is the interval
np.linspace(a, b, i) : i is the number of array element between a and b
Arrays filled with logarithmic sequences
>>> import numpy as np
>>> np.logspace(0, 2, 5)
array([ 1. , 3.16227766, 10. , 31.6227766 ,
100. ])
SUPPLEMENT
5 data points between 1 to 100
Meshgrid arrays
>>> import numpy as np
>>> x = np.array([-1, 0, 1])
>>> y = np.array([-2, 0, 2])
>>> X, Y = np.meshgrid(x, y)
>>> X
array([[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]])
>>> Y
array([[-2, -2, -2],
[ 0, 0, 0],
[ 2, 2, 2]])
>>> Z = (X + Y) ** 2
>>> Z
array([[9, 4, 1],
[1, 0, 1],
[1, 4, 9]], dtype=int32)
Creating uninitialized arrays
>>> import numpy as np
>>> np.empty(3, dtype=np.float)
array([3.50989482e-316, 0.00000000e+000, 6.46572085e+170])
Creating arrays with properties of other arrays
>>> import numpy as np
>>> def f(x):
... y = np.ones_like(x) # compute with x and y
... return y
>>> f([[1,2,3,4],[3,4,5,6]])
array([[1, 1, 1, 1],
[1, 1, 1, 1]])
>>> f(np.array([[1,2,3,4],[3,4,5,6]]))
array([[1, 1, 1, 1],
[1, 1, 1, 1]])
Creating matrix arrays
>>> import numpy as np
>>> np.identity(4)
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
>>> np.eye(3, k=1)
array([[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.]])
>>> np.eye(3, k=-1)
array([[0., 0., 0.],
[1., 0., 0.],
[0., 1., 0.]])
>>> np.diag(np.arange(0, 20, 5))
array([[ 0, 0, 0, 0],
[ 0, 5, 0, 0],
[ 0, 0, 10, 0],
[ 0, 0, 0, 15]])
Indexing and slicing
One-dimensional arrays
>>> import numpy as np
>>> a = np.arange(0, 11)
>>> a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> a[0]
0
>>> a[-1]
10
>>> a[4]
4
Multidimensional arrays
>>> import numpy as np
>>> f = lambda m, n: n + 10 * m
>>> A = np.fromfunction(f, (6, 6), dtype=int)
>>> A
array([[ 0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15],
[20, 21, 22, 23, 24, 25],
[30, 31, 32, 33, 34, 35],
[40, 41, 42, 43, 44, 45],
[50, 51, 52, 53, 54, 55]])
>>> A[:, 1]
array([ 1, 11, 21, 31, 41, 51])
>>> A[1, :]
array([10, 11, 12, 13, 14, 15])
>>> A[:3, :3] # upper half diagonal block matrix
array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22]])
>>> A[3:, :3] # lower left off-diagonal block matrix
array([[30, 31, 32],
[40, 41, 42],
[50, 51, 52]])
>>> A[::2, ::2] # every second element starting from 0, 0
array([[ 0, 2, 4],
[20, 22, 24],
[40, 42, 44]])
>>> A[1::2, 1::3] # every second and third element starting from 1, 1
array([[11, 14],
[31, 34],
[51, 54]])
Views
>>> import numpy as np
>>> f = lambda m, n: n + 10 * m
>>> A = np.fromfunction(f, (6, 6), dtype=int)
>>> A
array([[ 0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15],
[20, 21, 22, 23, 24, 25],
[30, 31, 32, 33, 34, 35],
[40, 41, 42, 43, 44, 45],
[50, 51, 52, 53, 54, 55]])
>>> B = A[1:5, 1:5]
>>> B
array([[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34],
[41, 42, 43, 44]])
>>> B[:, :] = 0
>>> A
array([[ 0, 1, 2, 3, 4, 5],
[10, 0, 0, 0, 0, 15],
[20, 0, 0, 0, 0, 25],
[30, 0, 0, 0, 0, 35],
[40, 0, 0, 0, 0, 45],
[50, 51, 52, 53, 54, 55]])
>>> C = B[1:3, 1:3].copy()
>>> C
array([[0, 0],
[0, 0]])
>>> C[:, :] = 1 # this does not affect B since C is a copy of the view B[1:3, 1:3]
>>> C
array([[1, 1],
[1, 1]])
>>> B
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
Fancy indexing and boolean-valued indexing
>>> import numpy as np
>>> A = np.linspace(0, 1, 11)
>>> A
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> A[np.array([0, 2, 4])]
array([0. , 0.2, 0.4])
>>> A[[0, 2, 4]] # The same thing can be accomplished by indexing with a Python list
array([0. , 0.2, 0.4])
>>> A > 0.5
array([False, False, False, False, False, False, True, True, True,
True, True])
>>> A[A > 0.5]
array([0.6, 0.7, 0.8, 0.9, 1. ])
>>> A = np.arange(10)
>>> indices = [2, 4, 6]
>>> B = A[indices]
>>> B[0] = -1 # this does not affect A
>>> A
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> A[indices] = -1 # this alters A
>>> A
array([ 0, 1, -1, 3, -1, 5, -1, 7, 8, 9])
>>> A = np.arange(10)
>>> B = A[A > 5]
>>> B[0] = -1 # this does not affect A
>>> A
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> A[A > 5] = -1 # this alters A
>>> A
array([ 0, 1, 2, 3, 4, 5, -1, -1, -1, -1])
Reshaping and resizeing
>>> import numpy as np
>>> data = np.array([[1, 2], [3, 4]])
>>> np.reshape(data, (1, 4))
array([[1, 2, 3, 4]])
>>> data.reshape(4)
array([1, 2, 3, 4])
>>> data = np.array([[1, 2], [3, 4]])
>>> data
array([[1, 2],
[3, 4]])
>>> data.flatten()
array([1, 2, 3, 4])
>>> data.flatten().shape
(4,)
>>> data = np.arange(0, 5)
>>> column = data[:, np.newaxis]
>>> column
array([[0],
[1],
[2],
[3],
[4]])
>>> row = data[np.newaxis, :]
>>> row
array([[0, 1, 2, 3, 4]])
Stack
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
Stack
np.stack((a,b))
array([[1, 2, 3],
[4, 5, 6]])
np.stack((a,b), axis=0)
array([[1, 2, 3],
[4, 5, 6]])
np.stack((a,b), axis=1)
array([[1, 4],
[2, 5],
[3, 6]])
vstack
np.vstack((a,b))
array([[1, 2, 3],
[4, 5, 6]])
np.vstack((a,b)).shape
(2, 3)
hstack
np.hstack((a,b))
array([1, 2, 3, 4, 5, 6])
np.hstack((a,b)).shape
(6,)
data = np.arange(5)
data
array([0, 1, 2, 3, 4])
data = data[:, np.newaxis]
data
array([[0],
[1],
[2],
[3],
[4]])
np.hstack((data, data, data))
array([[0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]])
dstack
np.dstack((a,b))
array([[[1, 4],
[2, 5],
[3, 6]]])
np.dstack((a,b)).shape
(1, 3, 2)
Delete
numpy.delete(arr, obj, axis=None)
delete element
Delete an element in Numpy Array by Index position
import numpy as np
# Delete element at index position 2
arr = np.array([4,5,6,7,8,9,10,11])
np.delete(arr, 2)
[ 4 5 7 8 9 10 11]
Delete multiple element in Numpy Array by Index position
import numpy as np
# Delete element at index positions 1,2 and 3
arr = np.array([4, 5, 6, 7, 8, 9, 10, 11])
np.delete(arr, [1,2,3])
[ 4 8 9 10 11]
Delete rows & columns from a 2D Numpy Array
Delete a column in Numpy Array by column number
import numpy as np
arr2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]])
arr2D
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
# Delete column at index 1
np.delete(arr2D, 1, axis=1)
[[11 13 11]
[21 23 24]
[31 33 34]]
Delete multiple columns in Numpy Array by column number
import numpy as np
arr2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]])
arr2D
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
# Delete column at index 2 & 3
np.delete(arr2D, [2,3], axis=1)
[[11 12]
[21 22]
[31 32]]
Delete a row in 2D Numpy Array by row number
import numpy as np
arr2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]])
arr2D
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
# Delete row at index 0 i.e. first row
np.delete(arr2D, 0, axis=0)
[[21 22 23 24]
[31 32 33 34]]
Delete multiple rows in Numpy Array by row number
import numpy as np
arr2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]])
arr2D
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
# Delete rows at ro1 1 & 2
np.delete(arr2D, [1, 2], axis=0)
[[11 12 13 11]]
Delete specific elements in 2D Numpy Array by index position
import numpy as np
arr2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]])
arr2D
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
# Delete element in row 0 and column 2 from 2D numpy array
np.delete(arr2D, 2)
[11 12 11 21 22 23 24 31 32 33 34]
import numpy as np
arr2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]])
arr2D
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
#'Delete element from 2D numpy array by row and column position'
def deleteFrom2D(arr2D, row, column):
return np.delete(arr2D, row * arr2D.shape[1] + column)
# Delete element in row 1 and column 1 from 2D numpy array
deleteFrom2D(arr2D, 1,1)
# Modified 2D Numpy Array by removing element at row 1 & column 1
[11 12 13 11 21 23 24 31 32 33 34]
Vectorized expreesions
Arithmetic operations
>>> import numpy as np
>>> x = np.array([[1, 2], [3, 4]])
>>> y = np.array([[5, 6], [7, 8]])
>>> x + y
array([[ 6, 8],
[10, 12]])
>>> y - x
array([[4, 4],
[4, 4]])
>>> x * y
array([[ 5, 12],
[21, 32]])
>>> y / x
array([[5. , 3. ],
[2.33333333, 2. ]])
>>> x * 2
array([[2, 4],
[6, 8]])
>>> 2 ** x
array([[ 2, 4],
[ 8, 16]], dtype=int32)
>>> y / 2
array([[2.5, 3. ],
[3.5, 4. ]])
>>> (y / 2).dtype
dtype('float64')
>>> x = np.array([1, 2, 3, 4])
>>> z = np.array([1, 2, 3, 4])
>>> x / z
array([1., 1., 1., 1.])
>>> z = np.array([[2, 4]])
>>> z.shape
(1, 2)
>>> x / z
array([[0.5, 0.5],
[1.5, 1. ]])
>>> zz = np.concatenate([z, z], axis=0)
>>> zz
array([[2, 4],
[2, 4]])
>>> x / zz
array([[0.5, 0.5],
[1.5, 1. ]])
>>> z = np.array([[2], [4]])
>>> z.shape
(2, 1)
>>> x / z
array([[0.5 , 1. ],
[0.75, 1. ]])
>>> zz = np.concatenate([z, z], axis=1)
>>> zz
array([[2, 2],
[4, 4]])
>>> x / zz
array([[0.5 , 1. ],
[0.75, 1. ]])
>>> x = x + y
>>> x += y
Elementwise functions
module | description |
---|---|
np.add(x,y) | x + y |
np.subtract(x,y) | x - y |
np.multiply(x,y) | x * y |
np.divide(x,y) | x / y |
np.matmul(A,B) | A @ B |
np.transpose(A) | A.T |
>>> import numpy as np
>>> x = np.linspace(-1, 1, 11)
>>> x
array([-1. , -0.8, -0.6, -0.4, -0.2, 0. , 0.2, 0.4, 0.6, 0.8, 1. ])
>>> y = np.sin(np.pi * x)
>>> np.round(y, decimals=4)
array([-0. , -0.5878, -0.9511, -0.9511, -0.5878, 0. , 0.5878,
0.9511, 0.9511, 0.5878, 0. ])
>>> np.add(np.sin(x) ** 2, np.cos(x) ** 2)
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
>>> np.sin(x) ** 2 + np.cos(x) ** 2
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
>>> def heaviside(x):
... return 1 if x > 0 else 0
>>> heaviside(-1)
0
>>> heaviside(1.5)
1
>>> x = np.linspace(-5, 5, 11)
>>> y = []
>>> for i in list(x):
... y.append(heaviside(i))
>>> y
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
>>> heaviside = np.vectorize(heaviside)
>>> heaviside(x)
array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
>>> def heaviside(x):
... return 1.0 * (x > 0)
Aggregate functions
>>> import numpy as np
>>> np.unique([11, 11, 2, 2, 34, 34])
array([ 2, 11, 34])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])
>>> a = np.array(['a', 'b', 'b', 'c', 'a'])
>>> index, count = np.unique(a, return_counts=True)
>>> index
array(['a', 'b', 'c'], dtype='<U1')
>>> count
array([2, 2, 1], dtype=int64)
>>> np.bincount([1, 1, 2, 2, 3, 3], minlength=10)
array([0, 2, 2, 2, 0, 0, 0, 0, 0, 0], dtype=int64)
>>> data = np.random.normal(size=(15,15))
>>> np.mean(data)
0.04697496380370329
>>> data.mean()
0.04697496380370329
>>> data = np.random.normal(size=(5, 10, 15))
>>> data.sum(axis=0).shape
(10, 15)
>>> data.sum(axis=(0, 2)).shape
(10,)
>>> data.sum()
13.381766277412375
>>> data = np.arange(1,10).reshape(3,3)
>>> data
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> data.sum()
45
>>> data.sum(axis=0)
array([12, 15, 18])
>>> data.sum(axis=1)
array([ 6, 15, 24])
>>> data.cumsum()
array([ 1, 3, 6, 10, 15, 21, 28, 36, 45], dtype=int32)
>>> data.cumsum(axis=0)
array([[ 1, 2, 3],
[ 5, 7, 9],
[12, 15, 18]], dtype=int32)
>>> data.cumsum(axis=1)
array([[ 1, 3, 6],
[ 4, 9, 15],
[ 7, 15, 24]], dtype=int32)
>>> data.prod()
362880
>>> data.prod(axis=0)
array([ 28, 80, 162])
>>> data.prod(axis=1)
array([ 6, 120, 504])
>>> data.cumprod()
array([ 1, 2, 6, 24, 120, 720, 5040, 40320,
362880], dtype=int32)
>>> data.cumprod(axis=0)
array([[ 1, 2, 3],
[ 4, 10, 18],
[ 28, 80, 162]], dtype=int32)
>>> data.cumprod(axis=1)
array([[ 1, 2, 6],
[ 4, 20, 120],
[ 7, 56, 504]], dtype=int32)
# variance for population
>>> data.var()
6.666666666666667
>>> data.var(axis=0)
array([6., 6., 6.])
>>> data.var(axis=1)
array([0.66666667, 0.66666667, 0.66666667])
# standard deviation for population
>>> data.std()
2.581988897471611
>>> data.std(axis=0)
array([2.44948974, 2.44948974, 2.44948974])
>>> data.std(axis=1)
array([0.81649658, 0.81649658, 0.81649658])
>>> data.min()
1
>>> data.min(axis=0)
array([1, 2, 3])
>>> data.min(axis=1)
array([1, 4, 7])
>>> data.argmin()
0
>>> data.argmin(axis=0)
array([0, 0, 0], dtype=int64)
>>> data.argmin(axis=1)
array([0, 0, 0], dtype=int64)
>>> data.max()
9
>>> data.max(axis=0)
array([7, 8, 9])
>>> data.max(axis=1)
array([3, 6, 9])
>>> data.argmax()
8
>>> data.argmax(axis=0)
array([2, 2, 2], dtype=int64)
>>> data.argmax(axis=1)
array([2, 2, 2], dtype=int64)
Boolean arrays and conditional expressions
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4])
>>> b = np.array([4, 3, 2, 1])
>>> a < b
array([ True, True, False, False])
>>> np.all(a < b)
False
>>> np.any(a < b)
True
>>> if np.all(a < b):
... print("All elements in a are smaller than their corresponding element in b")
... elif np.any(a < b):
... print("Some elements in a are smaller than their corresponding element in b")
... else:
... print("All elements in b are smaller than their corresponding element in a")
Some elements in a are smaller than their corresponding element in b
>>> x = np.array([-2, -1, 0, 1, 2])
>>> x > 0
array([False, False, False, True, True])
>>> 1 * (x > 0)
array([0, 0, 0, 1, 1])
>>> x * (x > 0)
array([0, 0, 0, 1, 2])
>>> def pulse(x, position, height, width):
>>> return height * (x >= position) * (x <= (position + width))
>>> x = np.linspace(-5, 5, 11)
>>> pulse(x, position=-2, height=1, width=5)
array([0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0])
>>> pulse(x, position=1, height=1, width=5)
array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
>>> def pulse(x, position, height, width):
>>> return height * np.logical_and(x >= position, x <= (position + width))
>>> x = np.linspace(-4, 4, 9)
>>> np.where(x < 0, x**2, x**3)
array([16., 9., 4., 1., 0., 1., 8., 27., 64.])
>>> np.select([x < -1, x < 2, x >= 2],
... [x**2 , x**3 , x**4])
array([ 16., 9., 4., -1., 0., 1., 16., 81., 256.])
>>> np.choose([0, 0, 0, 1, 1, 1, 2, 2, 2],
... [x**2, x**3, x**4])
array([ 16., 9., 4., -1., 0., 1., 16., 81., 256.])
>>> np.nonzero(abs(x) > 2)
(array([0, 1, 7, 8], dtype=int64),)
>>> x[np.nonzero(abs(x) > 2)]
array([-4., -3., 3., 4.])
>>> x[abs(x) > 2]
array([-4., -3., 3., 4.])
Set operations
>>> import numpy as np
>>> a = np.unique([1, 2, 3, 3])
>>> b = np.unique([2, 3, 4, 4, 5, 6, 5])
>>> np.in1d(a, b)
array([False, True, True])
>>> 1 in a
True
>>> 1 in b
False
>>> np.all(np.in1d(a, b))
False
>>> np.union1d(a, b)
array([1, 2, 3, 4, 5, 6])
>>> np.intersect1d(a, b)
array([2, 3])
>>> np.setdiff1d(a, b)
array([1])
>>> np.setdiff1d(b, a)
array([4, 5, 6])
Operations on arrays
>>> import numpy as np
>>> data = np.arange(9).reshape(3, 3)
>>> data
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.transpose(data)
array([[0, 3, 6],
[1, 4, 7],
[2, 5, 8]])
>>> data = np.random.randn(1, 2, 3, 4, 5)
>>> data.shape
(1, 2, 3, 4, 5)
>>> data.T.shape
(5, 4, 3, 2, 1)
Matrix and vector operations
>>> import numpy as np
>>> A = np.arange(1, 7).reshape(2, 3)
>>> A
array([[1, 2, 3],
[4, 5, 6]])
>>> B = np.arange(1, 7).reshape(3, 2)
>>> B
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.dot(A, B)
array([[22, 28],
[49, 64]])
>>> np.dot(B, A)
array([[ 9, 12, 15],
[19, 26, 33],
[29, 40, 51]])
>>> A = np.arange(9).reshape(3, 3)
>>> A
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> x = np.arange(3)
>>> x
array([0, 1, 2])
>>> np.dot(A, x)
array([ 5, 14, 23])
>>> A.dot(x)
array([ 5, 14, 23])
>>> A = np.random.rand(3,3)
>>> B = np.random.rand(3,3)
>>> Ap = np.dot(B, np.dot(A, np.linalg.inv(B))) # or Ap = B.dot(A.dot(np.linalg.inv(B)))
>>> A = np.matrix(A)
>>> B = np.matrix(B)
>>> Ap = B * A * B.I
>>> A = np.asmatrix(A)
>>> B = np.asmatrix(B)
>>> Ap = B * A * B.I
>>> Ap = np.asarray(Ap)
>>> np.inner(x, x)
5
>>> np.dot(x, x)
5
>>> y = x[:, np.newaxis]
>>> y
array([[0],
[1],
[2]])
>>> np.dot(y.T, y)
array([[5]])
>>> x = np.array([1, 2, 3])
>>> np.outer(x, x)
array([[1, 2, 3],
[2, 4, 6],
[3, 6, 9]])
>>> np.kron(x, x)
array([1, 2, 3, 2, 4, 6, 3, 6, 9])
>>> np.kron(x[:, np.newaxis], x[np.newaxis, :])
array([[1, 2, 3],
[2, 4, 6],
[3, 6, 9]])
>>> np.kron(np.ones((2,2)), np.identity(2))
array([[1., 0., 1., 0.],
[0., 1., 0., 1.],
[1., 0., 1., 0.],
[0., 1., 0., 1.]])
>>> np.kron(np.identity(2), np.ones((2,2)))
array([[1., 1., 0., 0.],
[1., 1., 0., 0.],
[0., 0., 1., 1.],
[0., 0., 1., 1.]])
>>> x = np.array([1, 2, 3, 4])
>>> y = np.array([5, 6, 7, 8])
>>> np.einsum("n,n", x, y)
70
>>> np.inner(x, y)
70
>>> A = np.arange(9).reshape(3, 3)
>>> B = A.T
>>> np.einsum("mk,kn", A, B)
array([[ 5, 14, 23],
[ 14, 50, 86],
[ 23, 86, 149]])
>>> np.alltrue(np.einsum("mk,kn", A, B) == np.dot(A, B))
True
Linear algebra summary
>>> import numpy as np
# Unit matrix
>>> np.eye(n)
# Diagonal matrix
>>> np.diag(x)
# Dot product, Inner product
>>> np.dot(a, b)
# Trace
>>> np.trace(x)
# Matrix Determinant
>>> np.linalg.det(x)
# Inverse of a matrix
>>> np.linalg.inv(x)
# Eigenvalue, Eigenvector
>>> w, v = np.linalg.eig(x)
# Singular Value Decomposition
>>> u, s, vh = np.linalg.svd(A)
# Solve a linear matrix equation
>>> np.linalg.solve(a, b)
# Compute the Least-squares solution
>>> m, c = np.linalg.lstsq(A, y, rcond=None)[0]
Generating random numbers
rand : discrete uniform distribution
>>> import numpy as np
>>> np.random.rand(10) # 10 random numbers in range : [0,1)
array([0.18336001, 0.40406785, 0.42358141, 0.80555542, 0.87815471,
0.85026875, 0.11360124, 0.78805191, 0.38712532, 0.68707246])
>>> np.random.rand(3, 5) # 15=3*5 random numbers in range : [0,1)
array([[0.40784588, 0.78406288, 0.12970014, 0.16819594, 0.8416527 ],
[0.43929381, 0.07277906, 0.42691374, 0.05579255, 0.95001246],
[0.58211827, 0.88796904, 0.56544585, 0.77061755, 0.16551513]])
randn : Gaussian(standard normal distribution)
>>> import numpy as np
>>> np.random.randn(10) # 10 random numbers in range : (-oo,oo)
array([ 0.58711644, 0.04700508, -1.10859032, -0.78977472, 2.64137167,
-0.01833935, 0.03531587, -1.72592648, 0.66461845, -0.36460468])
>>> np.random.randn(3, 5) # 15=3*5 random numbers in range : (-oo,oo)
array([[-0.99387193, 0.71975003, -0.719061 , -0.51130777, -0.18149095],
[-0.95578814, 0.23776812, -1.80650151, 0.86778844, -1.12507707],
[-0.88193264, 2.44759966, -0.27246929, 1.8909227 , -1.21857409]])
numpy.random.randint(low, high=None, size=None)
random integers from the “discrete uniform” distribution
>>> import numpy as np
>>> np.random.randint(300, size=10)
array([204, 11, 186, 56, 282, 188, 144, 77, 74, 70])
>>> np.random.randint(10, 20, size=10)
array([18, 15, 13, 19, 13, 15, 19, 11, 14, 11])
>>> np.random.randint(10, 20, size=(3, 5))
array([[11, 18, 10, 10, 16],
[12, 14, 19, 13, 14],
[16, 15, 14, 11, 17]])
SUPPLEMENT
for randint, size means the number of random numbers
if high = None, [0,low)
if high exist, [low,high)
random : continuous uniform distribution
>>> import numpy as np
>>> np.random.random(10) # 10 random numbers in range : [0,1)
array([0.34713881, 0.30399416, 0.41043101, 0.32724989, 0.56059852,
0.73058418, 0.81791713, 0.66873001, 0.32567901, 0.28508951])
>>> np.random.random((3,5)) # 15=3*5 random numbers in range : [0,1)
array([[0.40258795, 0.10722707, 0.31550996, 0.22636655, 0.74710598],
[0.65378433, 0.82984828, 0.57223887, 0.46599507, 0.75786503],
[0.44165555, 0.83216394, 0.1828639 , 0.87262362, 0.28863524]])
Additional : choice
>>> np.random.choice(7,10)
array([4, 5, 2, 3, 5, 1, 1, 1, 5, 6])
>>> np.random.choice(8,10)
array([7, 6, 1, 6, 4, 7, 2, 3, 3, 2])
>>> np.random.choice(9,10)
array([2, 8, 3, 1, 5, 6, 8, 6, 6, 4])
>>> np.random.choice(10,10)
array([1, 6, 7, 1, 6, 5, 9, 9, 7, 2])
>>> np.random.choice(11,10)
array([ 6, 1, 4, 1, 3, 1, 6, 10, 10, 0])
>>> np.random.choice(12,10)
array([ 8, 6, 2, 9, 11, 6, 0, 4, 7, 3])
random variable
>>> import numpy as np
>>> np.random.seed(123456789);
>>> rv = np.random.RandomState(123456789)
>>> rv.randn(2, 4)
array([[ 2.212902 , 2.1283978 , 1.8417114 , 0.08238248],
[ 0.85896368, -0.82601643, 1.15727052, 1.37591514]])
>>> rv.chisquare(1, size=(2, 2))
array([[1.26859720e+00, 2.02731988e+00],
[2.52605129e-05, 3.00376585e-04]])
>>> rv.standard_t(1, size=(2, 3))
array([[ 0.59734384, -1.27669959, 0.09724793],
[ 0.22451466, 0.39697518, -0.19469463]])
>>> rv.f(5, 2, size=(2, 4))
array([[ 0.77372119, 0.1213796 , 1.64779052, 1.21399831],
[ 0.45471421, 17.64891848, 1.48620557, 2.55433261]])
>>> rv.binomial(10, 0.5, size=10)
array([8, 3, 4, 2, 4, 5, 4, 4, 7, 5])
>>> rv.poisson(5, size=10)
array([7, 1, 3, 4, 6, 4, 9, 7, 3, 6])
Clipping
OUTPUT
List of posts followed by this article
Reference