Basic usage of Numpy

1. Create an array with Numpy

numpy.array(object): to create an array, unlike array.array(typecode [, initializer]), array.array() can only create one-dimensional arrays

Numpy.range (start, stop, step, dtype = none): create a one-dimensional array (step is the best integer) starting from start and ending at stop (excluding stop), with step as the step step. Dtype defaults to integer

numpy.linspace(start, stop, num=50,; endpoint=True,; retstep=False,; dtype=None,; axis=0): creates an array of 50 elements starting from start and ending from stop (including stop by default); num specifies the number of array elements; when endpoint is False, the array does not contain stop; the output array element is float by default

All the arrays created by the above functions return the type of ndarray

import numpy as np

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

ndarray_2 = np.arange(1, 9)

ndarray_3 = np.linspace(1, 9, 9)


2. Method of darray object

1.ndarray.ndim: returns the dimension of the array

2.ndarray.shape: returns the size of the array

3.ndarray.reshape(shape): returns a new array in shape format

4.ndarray.size: returns the total number of array elements

5.ndarray.dtype: returns the type of array element

6.ndarray.itemsize: returns the size of array elements in bytes

import numpy as np

x = np.linspace(1,18,18,dtype=int).reshape(2,3,3)
print(x.ndim)# 3
print(x.size)# 18
print(x.dtype)# int32
print(x.itemsize)# 4


3.numpy creates a special array (the element type of the array is float by default)

numpy.empty(shape, dtype=float, order = 'C'): create a random array

Numpy.empty'like (prototype, dtype = None, order ='K ', subok = True, shape = None): returns a new array with the same shape and type as the given array

Shape: controls the shape of the array, which is an int or an int tuple. For example, if shape is 3, then create an array of 3x3, if shape is (2,3), then create an array of 2x3

order: control whether the storage is dominated by behavior or column

import numpy as np

arr = np.empty((2,3))

a = np.arange(6).reshape(2,3)
arr_like = np.empty_like(a)


numpy.zeros(shape, dtype=float, order='C '): create an all zero array

Numpy.zeros'like (a, dtype = none, order ='k ', subok = true, shape = none): create a new all zero array with the same shape and type as the given array a

import numpy as np

arr_zero = np.zeros((2,3), dtype=int)

a = np.arange(6, dtype=float).reshape(2,3)
arr_zero_like = np.zeros_like(a)


numpy.ones(shape, dtype=None, order='C '): create an all 1 array

Numpy.ones'like (a, dtype = none, order ='k ', subok = true, shape = none): create an all 1 array with the same shape and type as the given array a

import numpy as np

arr_ones = np.ones((3,3), dtype=int)

a = np.arange(9, dtype=float).reshape(3,3)
arr_ones_like = np.ones_like(a)


Numpy. Full (shape, fill'u value, dtype = none, order ='c '): create a fill array filled with fill'u value

Numpy. Full'like (a, fill'value, dtype = none, order ='k ', subok = true, shape = none): create a filled array with the same shape and type as the given array a

import numpy as np

arr_full = np.full((2,3), 3)

a = np.arange(6)
arr_full_like = np.full_like(a, 1)


Numpy. Eye (n, M = none, k = 0, dtype = < class' float '> and order ='c'): create an array with diagonal elements of 1 and other elements of 0

M: the default value is N, which is to create an array of NxN

If K: K is a positive number, then the diagonal moves up by K; if K is a negative number, then the diagonal moves down by K; if k > m, then the array elements are all 0

numpy.identity(n, dtype=None): create an nxn array with a diagonal element of 1, and the element type defaults to float

import numpy as np

arr_eye = np.eye(3)

arr_eye2 = np.eye(3, k=1)

arr_eye3 = np.eye(3, k=3)

arr_id = np.identity(3)


4. Index of array

4.1 index of one-dimensional array

The index of a one-dimensional array is similar to that of a list

import numpy as np

a = np.arange(10)
print(a[-1])# 9
print(a[5:])#[5 6 7 8 9]
print(a[-5:10])#[5 6 7 8 9]
# When the first parameter is less than the second, the last parameter should be a negative number, indicating the index from the back to the front
print(a[-2:2:-1])#[8 7 6 5 4 3]
# Flip
print(a[::-1])#[9 8 7 6 5 4 3 2 1 0]
print(a[5::2])#[5 7 9]
# Integer index,Index the second, last fourth, and fifth element of the array
print(a[[2,-4,5]])#[2 6 5]

# The index method of subscript occupies the same storage space as the original array. Modify b At that time, a It will also be modified
b = a[1:3]
b[0] = 100
# The list index does not occupy the same storage space as the original array. Modify c At that time, a2 Will not be modified
a2 = np.arange(10)
c = a2[[0,1,2]]
c[0] = 100


4.2 index of 2D array

import numpy as np

a = np.arange(24).reshape(4,6)
# Take the first element of the first and second lines
print(a[0,0], a[1,0]) 
# Take all elements of the first row, index subscripts of the first row and the first column are 0, and so on 
# Take all elements in the first column
print(a[:, 0])
# Take some elements from the first line to the third line
print(a[0:3, :3])
# Flip
print(a[::-1, ::-1])

#a[i:j, i:j] Row before comma, column after comma


4.3 index of 3D array

import numpy as np

a = np.arange(24).reshape(2,3,4)
# You can put an array a Think of it as a 2-story house with 3 floors x4 Rooms, the first index value indicates which floor is located, and the next two indexes are similar to 2D array
print(a[0, :, :])
# When it's all about:You can use one...replace
# Index the first row of the first layer, the elements of the first column
print(a[0, 0, 0])
# Index the last column elements of two layers


5.Numpy.random module

numpy.random.rand(d0, d1, d2,..., dn): generates a random array whose element values are between 0-1. The shape of the array is determined by the parameters passed in: when no parameters are passed in, an element is generated; when a parameter is passed in, a one-dimensional array is generated according to the size of the parameter; when two parameters are passed in, a two-dimensional array is generated

numpy.random.randn(d0,d1,d2,...,dn): generates a number or array that obeys the standard normal distribution. The shape of the array is determined by the passed in parameters (d1,d2,...dn)

import numpy as np

arr1 = np.random.rand()
print(arr1, '\n')
arr2 = np.random.rand(6)
print(arr2, '\n')
arr3 = np.random.rand(2,3)
print(arr3, '\n')
arr4 = np.random.randn(2,3,4)


Numpy. Random. Random (low, high=None, size=None, dtype ='l '): returns a random integer from small to large. If high=None, the range of the integer is [0, low], otherwise [low, high]. If size=None, a random integer is generated. Otherwise, the corresponding array is generated according to size, the same below

import numpy as np

arr1 = np.random.randint(5)
arr2 = np.random.randint(1, 10, (2,3))
# When size When there is only one parameter before, size Parameters to be written as size=(a,b)
arr3 = np.random.randint(10,size=(2,3))


numpy.random.normal(loc=0.0, scale=1.0, size=None): generates a number or array that obeys the normal distribution. loc is the mean value of the normal distribution, and scale is the standard deviation of the normal distribution

numpy.random.uniform(low=0.0, high=1.0, size=None): generate a number or array subject to uniform distribution, all values generated are greater than or equal to low, less than high

numpy.random.poisson(lam=1.0, size=None): generate a number or array of Poisson distributions that obey lam=1.0

import numpy as np

arr1 = np.random.normal(0, 1, (2,3))# Obey standard normal distribution
arr2 = np.random.uniform(3, 5, (2,3))
arr3 = np.random.poisson(size=(2,3))


numpy.random.choice(a, size=None, replace=True, p=None): a random sample is generated from a given one-dimensional array a, and replace sets whether to replace the sample; p sets the probability that each number in a is selected, if not given, then each number is subject to uniform distribution;

import numpy as np

a = np.arange(5)
arr1 = np.random.choice(a, (2,3))
arr2 = np.random.choice(a, 5, p=[0.1,0.2,0,0.7,0])


numpy.random.shuffle(a): randomly scramble an array, and multi-dimensional arrays are randomly arranged along the first axis. The function returns None, and the original array is changed

import numpy as np

a = np.arange(12)

b = np.arange(12).reshape(3,4)


numpy.random.seed(seed=None): used to seed random numbers


6. Statistical function

Numpy can be used to sum and average arrays

Numpy. Sum (a, axis = none, dtype = none, out = none, keepdims = < no value >, initial = < no value >):: used to sum array elements, axis=0: sum each column, axis=1: sum each row

import numpy as np

data1 = np.sum(np.arange(10).reshape(2,5))

data2 = np.sum(np.arange(10).reshape(2,5), axis=0)

data3 = np.sum(np.arange(10).reshape(2,5), axis=1)

data = np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)#Manual example, do not understand why the result is 1


Numpy.mean (a, axis = none, dtype = none, out = none, keepdims = < no value >): used to find the mean value

import numpy as np

data1 = np.mean(np.arange(10).reshape(2,5))

data2 = np.mean(np.arange(10).reshape(2,5), axis=0)

data3 = np.mean(np.arange(10).reshape(2,5), axis=1)


Numpy. Average (a, axis = none, weights = none, returned = flat): used to find the weighted average, weights is the array used for weighting

import numpy as np

data = np.average([5,10],weights=[1,2])#Amount to(1*5+2*10)/(1+2)

Var (a, axis=None): used to find variance;

numpy.std(a, axis=None): used to find the standard deviation;

numpy.max(a, axis=None): used to find the maximum value;

numpy.min(a, axis=None): used to find the minimum value;


7. Matrix operation (better with matlab)

The module of Numpy for matrix operation is Numpy.linaling

Numpy. Translate (a, axes = none): for matrix transposition, or you can use darray. T directly, b): calculate the inner product of vector in one dimension; calculate the matrix multiplication in two dimensions, or (b)

numpy.trace(a, offset=0): used to calculate the sum of diagonal elements of a matrix

Linaling.det (a): used to calculate determinants

Linaling.eig (a): used to calculate the eigenvalues and eigenvectors of a square matrix

Linaling.inv (a): for inverse matrix

Linaling. Solve (a, b): solve linear equations Ax=b

Linaling.qr (a, mode ='reduced '): QR decomposition for Matrices

Linaling.svd (a, full ﹣ matrices = 1, compute ﹣ UV = 1): singular value decomposition for Matrices


For more usage, please refer to: Numpy manual

Keywords: Python less MATLAB

Added by shyonne2004 on Tue, 10 Dec 2019 23:23:20 +0200