Writing

Scientific Computing (1) — NumPy in Detail

Preface: NumPy is a matrix-based numerical computing module built on multidimensional ndarrays. Official docs: https://docs.scipy.org/doc/numpy/user/index.html

Preface: NumPy is a matrix-based numerical computing module whose foundation is the multidimensional array ndarray. Official documentation: (https://docs.scipy.org/doc/numpy/user/index.html)

What Is ndarray?

A fixed multidimensional array of elements of the same type. (Note the emphasized words.)

Creating ndarray

Code:

import numpy as np

np.array([[1,2,3],[4,5,6]])
np.zeros((4,5))
np.ones((2,3,4))#生成一个二维的三行四列 ,值全为1的数组
np.random.randint(1,20,size=(4,5))
np.arange(1,9,2)
#生成等差数列
np.linspace(1,10,4)
#生成等比数列
np.logspace(0,1,3,base=2)#表示在2的0次方和2的1次方之间生成3个等比数列

As shown:

image

Generating Random Arrays

In[11]: np.random.rand(2,3)#生成一个形状为2*3大小为[0,1)的数组
Out[11]:
array([[0.26931669, 0.22987196, 0.26229279],
       [0.24496358, 0.5316016 , 0.24352748]])

ndarray Attributes

randint(low, high=None, size=None, dtype='l'); shape gives dimensions; dtype gives element type.

a=np.random.randint(1,3,size=(2,3))
print(a)
print(a.shape)
print(a.dtype)

[[1 1 2] [1 1 2]] (2, 3) int32

Reshaping

reshape changes the shape of a copy; shape assignment changes in place.

arr=np.random.randint(1,5,8)
arr.reshape(2,4)
arr

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

arr.shape=(4,2)
arr

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

ndarray Operations

Matrix product:

np.dot(arr01,arro2)
  • ndarray slicing

  • Boolean slicing

arry10=np.random.randint(1,20,size=(4,2,4))
arry10[2:,0,1:3]

([[17, 9], [ 7, 4]])

  • Fancy indexing
arry10[[True,False,False,False]]

array([[[14, 12, 13, 18], [ 5, 7, 5, 16]]])

Matrix Transpose

arr=np.random.ranint(1,10,size=(3,4))
arr.transpose
arr.T

Aggregation Functions

Mean, variance, standard deviation:

#二元函数比较大小np.greater(arr1,arr2),返回的是布尔类型的值
np.greater([4,2],[2,2])
>>>array([ True, False])
#求平均值
arr1=np.array([[1,2,3,4],[2,3,4,5]])
arr1
>>>array([[1, 2, 3, 4],
       [2, 3, 4, 5]])
arr1.mean(axis=0)#求每一列的平均值
>>>array([1.5, 2.5, 3.5, 4.5])
arr1.mean(axis=1)#求每一行的平均值
>>>array([2.5, 3.5])
#求方差
np.var(arr,axis=1)
>>>array([1.25, 1.25])
#求标准差
arr1.std(axis=1)
>>>array([1.11803399, 1.11803399])

np.where:

#np.where(condition,arr1,arr2)
#例子:将np.nan换成0
a1=np.array([
    [1,2,np.NaN],
    [1,2,np.pi],
    [1,2,np.e],
])
condition=np.isnan(a1)
np.where(condition,0,a1)

array([[1. , 2. , 0. ], [1. , 2. , 3.14159265], [1. , 2. , 2.71828183]])

np.unique for deduplication:

arr2=np.array([0,1,2,11,1,1])
np.unique(arr2)

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

Postscript: Still learning — updates will come slowly. We encourage each other.

You might also like: my machine learning pandas series, matplotlib series, and calculus series.