[PYTHON] Numpy basic calculation memo

A memo of the one often used in Python's numerical calculation library, Numpy. It is often imported under the name np. Will be updated from time to time.

import numpy as np

array Make a line.

>>> np.array([1, 2, 3])
array([1, 2, 3])
>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
       [3, 4]])

T Make a transposed matrix.

>>> a = np.array([[1, 3], [2, 1]])
>>> a
array([[1, 3],
       [2, 1]])
>>> a.T
array([[1, 2],
       [3, 1]])

zeros, ones zeros is 0 and ones is filled with 1 to produce a matrix of the specified form.

>>> np.zeros(3)
array([ 0.,  0.,  0.])
>>> np.zeros([3, 3])
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> np.ones(3)
array([ 1.,  1.,  1.])
>>> np.ones([3, 3])
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])

eye Make an identity matrix.

>>> np.eye(3)
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

diag Make a diagonal matrix.

>>> np.diag([1, 2, 3])
array([[1, 0, 0],
       [0, 2, 0],
       [0, 0, 3]])

vstack, hstack Used for matrix composition. The usage is as follows.

>>> a = np.array([1, 1, 1])
>>> b = np.array([2, 2, 2])
>>> np.vstack([a, b])
array([[1, 1, 1],
       [2, 2, 2]])
>>> np.hstack([a, b])
array([1, 1, 1, 2, 2, 2])

dot Calculate the inner product.

>>> np.dot([1, 2, 3], [1, 2, 3])
14

cross Calculate the cross product.

>>> np.cross([0, 1], [1, 0])
array(-1)

flatten Change to a one-dimensional array

>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> a.flatten()
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

random.rand Generate a matrix of random numbers.

>>> np.random.rand(3)
array([ 0.37043199,  0.67058649,  0.53891633])
>>> np.random.rand(2, 3)
array([[ 0.50614319,  0.04483549,  0.39542568],
       [ 0.04853891,  0.55439793,  0.81737454]])

Recommended Posts

Numpy basic calculation memo
Numpy [Basic]
Flask basic memo
[Python] Numpy memo
python numpy array calculation
Python basic memo --Part 2
Basic Python command memo
Python basic grammar memo
Python basic memo --Part 1
Python Basic --Pandas, Numpy-
[Python] Calculation method with numpy
Python Basic Grammar Memo (Part 1)
My reverse numpy / scipy memo
virtualenv Basic command usage memo
Python basic grammar (miscellaneous) Memo (3)
Python basic grammar (miscellaneous) Memo (2)
Multidimensional array calculation without Numpy
Python basic grammar (miscellaneous) Memo (4)
[Scientific / technical calculation by Python] Basic operation of arrays, numpy
Multidimensional array calculation without Numpy Part 2
[Memo] Small story of pandas, numpy
Linux command (basic in basic) personal memo
BESS Development Memo # 01: BESS Installation and Basic Usage