泓熠 (HY)
Copyright © 2026, 泓熠 (HY).
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
apt install python3-numpy # For debian 12/13.
pip #
pipx #
install numpy
提供新的数据类型(类对象): numpy.ndarray
import numpy as np # 调用numpy包并取别名np
ndarray_example.ndim # 数组的维度
ndarray_example.shape # 一个元组, 反映 numpy.ndarray的shape, 元组的各元素为最高维度的长度至最低维度的长度
ndarray_example.size # 元素总个数, 等于各维度长度乘积
ndarray_example.dtype # 数组中元素类型, 同一个数组中所有元素类型相同
ndarray_example.itemsize # 数组中每个元素的字节大小
ndarray_example.dtype.itemsize # 同 ndarray_example.itemsize
import numpy as np
np.array(
[
[1, 2], #
[3, 4]
] # list: 需要创建数组的嵌套列表
) # ndarray: 将嵌套列表创建成的多维数组
ndarray_1.tolist() # list: 将多维数组转换后的普通嵌套列表
np.zeros( #
(3, 4), # tuple: 创建的 numpy.ndarray 的 shape, shape 元组中各元素依次为最高维度至最初维度的长度
dtype=np.int16 # str: 指定numpy.ndarray中的元素的数据类型, 可选参数默认为 numpy.float64
) # 创建 3 行 4 列的二维数组, 元素都为 0, 指定数组中的元素类型为 numpy.int16
np.ones( #
(2, 3), # tuple: 创建的 numpy.ndarray 的 shape
dtype=complex # str: 指定数组中的元素类型, 可选参数默认为 numpy.float64
) # 创建的 numpy.ndarray, 元素都为 1, 指定数组中的元素类型为 complex
np.zeros_like( # 模仿形状并产生数组
ndarray_eg # ndarray: 需要被模仿形状的数组
) # ndarray: 模仿 shape 产生的全0的数组
np.ones_like( #
ndarray_eg # ndarray: 需要被模仿形状的数组
) # ndarray: 模仿 shape 产生的全1的数组
np.empty( #
(2, 3), # tuple: 创建的数组的 shape
dtype=np.int32 # 指定数组中的元素数据类型, 可选参数默认为 numpy.float64
) # ndarray: 指定 shape 和元素数据类型的数组, 元素随机
np.random.random( #
(2, 3) # tuple: 创建的数组的 shape
) # ndarray: 指定 shape 的, 元素均为 [0,1) 的随机数的数组
np.random.rand( #
2, # *return_ndarray.shape
3
) # ndarray: 指定 shape 的, 元素均为 [0,1) 的随机数的数组
np.random.randn(
2, # *return_ndarray.shape
3 #
) # 指定 shape 的, 元素为从算术均值为0标准差为 1 的正态分布的随机数的数组
np.random.nomal(
0, # num: 算术均值
1, # num: 标准差
1024 # num: 元素个数
) # ndarray: 创建的指定条件的符合正态分布的一维数组
np.random.standard_normal(
size=None
) # ndarray: 创建的算术均值为0标准差为 1 的正态分布一维数组
np.random.rand() # ndarray: 元素为从 0 到 1 一组均匀分布的数
np.random.uniform(
1, # 下界限(含)
2, # 上界限(不含)
size=None # int/tuple: 数组的 shape
) # ndarray
np.arange(
1, # num: 起点(含), 可选参数默认为 0
6, # num: 终点(不含)
2, # num: 步长, 可选参数默认为 1
dtype=float64 # str: 生成的数组中的数据类型, 可选参数
) # ndarray: 创建的一维数组
np.random.randint( #
1, # int: 起点
3, # int/None: 终点, 若为 None 则生成范围为0到起点
6, # int/tuple: 数组的 shape
dtype='float64' # str: 数据类型
) # ndarray: 生成的从起点到终点的均匀分布的所及整数数组
np.linspace( #
-1, # num: 起点(含)
2, # num: 终点(不含)
5, # num: 元素个数
endpoint=True # bool: 是否包含终点, 可选参数默认为 True
) # 创建的从起点至终点的指定元素个数的 1D numpy.ndarray
np.logspace( #
1, # num: 10 的指数起点(含)
2, # num: 10 的指数终点(含)
3 # num: 元素个数
) # 创建从起点到终点的等比数列数组
np.meshgrid(
x, # 横坐标遍历的一维列表
y # 纵坐标遍历的一维列表
) # 生成的横坐标与纵坐标的网格点坐标矩阵
np.fromfunction( # 根据多元函数, 维度轴上的元素为自然数自变量, 其余元素为因变量
myfunction, # func: 多元函数名, 函数的元数等于数组的维度
(5, 4), # tuple: 数组 shape
dtype=int # str: 元素的数据类型, 可选参数默认为 float64
) # ndarray: 创建的数组
np.r_[ #
1: # num: 起点(含), 可选参数默认为 0
4: # num: 终点(不含)
1, # num: 步长, 可选参数默认为 1
0 # num: 其他元素, 不定长参数
] # ndarray: 创建的一维数组
np.marid( #
1:4:1, #
2:3:1 #
) # 生成的等差数列
ndarray_b = ndarray_a # 同一数组赋予不同的标识符, 拥有相同 id
ndarray_a.view() # 原数组的 view, 即以原数组作为 base 的新数组
ndarray_a[:] # 原数组的 view, 数组的所有用方括号的索引切片操作返回的都是数组的 view
ndarray_b.base # 新数组 y 的 base 属性为原数组
# 互为 base 与 view 的两个数组, 改变任一数组的形状, 另一数组不会改变, 但改变任一数组中的元素, 另一数组也会同时改变
ndarray_a.copy() # ndarray: 原数组的深拷贝
np.array(
ndarray_a # ndarray
) # ndarray: 指定 ndarray 的深拷贝
np.asarray(
ndarray_a # ndarray
) # ndarray: 指定 ndarray 的浅拷贝
ndarray_1[2, 3] # 相当于 np.array (ndarray_a.tolist()[2][3]), 索引号先定位最高维度, 最后定位最初维度
ndarray_1[-1] # 索引切片后的结果, 相当于 b[-1,:] 或 [-1,...], 当索引号个数少于维度时, 缺失的索引号被默认为完整切片即后面有若干个":"
ndarray_1[
4,
..., # 三个句点表示产生完整索引所需的冒号
5, #
0: # 起点索引号, 可选参数默认为0
6: # 终点索引号, 可选参数默认为-1
2 # 步长, 可选参数默认为1
] # 索引切片后的结果
ndarray_a[ #
np.array([[0, 1], [1, 2]]), #
np.array([[2, 1], [3, 3]]) # 索引方括号内部可以是单个或多个 numpy.ndarray, 也可以是元素为 numpy.ndarray 的列表, 每个 numpy.ndarray 索引一个维度, 多个 numpy.ndarray 必须有相同的 shape (同时索引各维度); 索引方括号中 numpy.ndarray 中各元素为指定的索引号
] # 指定索引号的元素
ndarray_a[
np.array(
[False,True],
[True,False]
) # 使用布尔 numpy.ndarray 进行索引: 若为布尔 1D numpy.ndarray 则其长度必须等于索引维度轴长; 若为布尔 nD numpy.ndarray 则其须与被索引的 numpy.ndarray 同 shape; True 代表选取, False 代表不选取
] # 选取的元素
for i in ndarray_a: # 对 nD numpy.ndarray 的最高维度迭代
for j in i: # 对 nD numpy.ndarray 的次高维度迭代
pass
ndarray_eg.T() # 转置后的矩阵
# C 风格迭代顺序: 从最初维度开始迭代, 最初维度轴坐标变化最快
# Fortran 风格迭代顺序: 从最高维度开始迭代, 最高维度轴坐标变化最快
ndarray_a.flat: # 对 nD numpy.ndarray 所有元素的迭代器, 迭代顺序 C 风格
ndarray_eg.ravel(
order='C' # 迭代顺序风格, 'C' 为 C 风格, 'F' 为 Fortran 风格, 可选参数默认为 'C', 可位置传参或关键字传参
) # 将数组以指定风格迭代顺序展平后的 1D numpy.ndarray, 原数组的 view
np.ravel(
ndarray_eg, # numpy.ndarray
order='C' # 迭代顺序风格
) # 将数组以指定风格迭代顺序展平后的 1D numpy.ndarray
ndarray_eg.flatten() # 将数组展平后的 1D numpy.ndarray, 原数组的 copy
np.reshape(
ndarray_eg, # ndarray:
(3, 4), # tuple: shape
order='C' # 迭代顺序风格
) # 把原数组的元素以指定迭代顺序组合成的指定形状的数组
ndarray_eg.reshape(
3, # shape
4 # 最后一个维度长度为 -1 意为自动计算其他维度轴长
) # 把原 numpy.ndarray 的元素以 C 风格迭代顺序组成指定形状的数组
np.resize(
ndarray_example, # ndarray
(3, 4 # shape 的最后一个维度轴长为 -1 意为自动计算其他维度轴长
) # 该元组为 shape
) # changeobject: 把原数组以 C 风格迭代顺序无条件分成指定形状的数组, 若新形状大于旧形状则重复填充
ndarray_example.resize( #
( #
3, # 数组从最高维度至最初维度的长度, 不定长参数
4 # 最后一个维度长度可设置为 -1, 意为自动计算其他维度长度
), # 该元组为 shape, 也可以不写元组直接拆开写成多个整数
refcheck=True # 检查是否有另外的对象与此 nympy.ndarray 共用内存缓冲区, 如果有则重新分配内存, 可选参数默认为 True
) # ndaray: 把原 numpy.ndarray 的元素以C风格迭代顺序组合成指定形状的数组, 若新形状大于旧形状则用零填充
ndarray_eg.astype( # 转换数据类型
np.int32 # 数据类型
)
ndarray_eg.tostring() # 转换为字符串类型
ndarray_eg.tobytes() # 转换为 bytes 类型
np.unique(
ndarray_eg # ndarray: 需要去重的数组
) # ndarray: 元素去重后的数组
np.all(
ndarray_eg # ndarray[bool]: 元素为布尔值的数组
) # bool: 数组中所有元素为 True 才返回 True, 否则返回 False
np.any(
ndarray_eg # ndarray[bool]: 元素为布尔值的数组
) # bool: 数组中只要存在 True 则返回 True, 否则返回 False
np.where(
ndarray_eg, # ndarray[bool]: 元素为布尔值的数组
1, # num: True 元素变为的数据
0 # num: False 元素变为的数据
)
np.logical_and(
ndarray_a, # ndarray[bool]
ndarray_b # ndarray[bool]
) # ndarray[bool]
np.logical_or(
ndarray_a, # ndarray[bool]
ndarray_b # ndarray[bool]
) # ndarray[bool]
np.max(
axis=0
)
np.min(
axis=0
)
np.mean(
axis=0
)
np.argmax(
ndarray_eg, # ndarray: 数组
axis=0 # 可选参数默认为拉平成一维数组后的索引号
) # int/ndarray:
np.argmin(
ndarray_eg, # ndarray: 数组
axis=0 # 可选参数默认为拉平成一维数组后的索引号
) # int/ndarray:
np.median()
np.mean()
np.std()
np.var()
# 广播机制, 将两个形状不同的数组变成同样的形状再进行计算, 缺失值通过复制自身对应的数据进行填充
# 广播机制的条件: 两数组某一维度等长或者其中一个数组某一维度长度为 1
np.matmul(
ndarray_a, # ndarray/num: 乘数
ndarray_b # ndarray/num: 乘数
) # ndarray: 乘法结果矩阵
np.dot( # 禁止矩阵乘数量
ndarray_a, # ndarray: 乘数
ndarray_b # ndarray: 乘数
) # ndarray: 乘法结果矩阵
import numpy as np
np.nan # NaN 数据类型 (Not a Number)
sum(
ndarray_eg # ndarray, 被求和的数组
) # num, 数组中所有元素代数和
ndarray_1 + ndarray_2↲ # 对应元素相加的结果新数组
np.add(
ndarray_1,
ndarray_2
) # 同ndarray_1 + ndarray_2
ndarray_1 * ndarray_2 # 对应元素相乘的结果新数组
np.sin(ndarray_a) # 所有元素的正弦值组成的新数组
np.cos(ndarray_a) # 所有元素的余弦值组成的新数组
np.exp(ndarray_a) # 回所有元素的自然对数组成的新数组
np.sqrt(ndarray_a) # 所有元素的算术平方根组成的新数组
ndarray_1 @ ndarray_2 # 矩阵乘法结果
ndarray_1.dot(ndarray_2) # 同 ndarray_1 @ ndarray_2
ndarray_1.sum() # 所有元素的加和
ndarray_1.min() # 最小元素
ndarray_1.max() # 返回最大元素
np.floor(
ndarray_1 # 要对其进行向下取整的数组
) # 对每个元素向下取整后生成的新 ndarray
ndarray_b.sum(
axis=0 # 维度轴的编号, 0 为最初维度轴, 依此类推
)↲ # object: 将对应元素都加到对应编号的维度轴上, 将数组压扁
ndarray_b.cumsum(
axis=1 # 维度轴的编号, 0 为最初维度轴, 依此类推
) # object: 沿着对应编号的维度轴向, 将元素改为从起点到元素自身的累加和
np.vstack(
(ndarray_a, ndarray_b) # 该元组里面存储若干个 ndarray 对象
)↲ # 将若干个 numpy.ndarray 按第二维度(行)堆叠
np.hstack(
(ndarray_a, ndarray_b) # 该元组里面存储若干个 ndarray 对象
) # 将若干个 numpy.ndarray 按第一维度(列)堆叠
np.column_stack(
(ndarray_a, ndarray_b) # 该元组里面存储若干个 numpy.ndarray
) # 将 1D numpy.ndarray 转置后按第二维度堆叠到二维数组之后
np.hsplit( # 在第一维度轴(列)上切开数组
ndarray_example, # 要拆分的 numpy.ndarray
(3, 4) # 若为单个整数则表示均分后的个数, 若为元组则其各元素定位要在第几列后切开数组
) # 一个列表, 其元素为沿着最初维度方向切开后的各 ndarray
np.vsplit( # 在第二维度轴(行)上切开数组
ndarray_example, # 要拆分的 numpy.ndarray
3, # 若为单个整数则表示均分后的个数, 若为元组则其各元素定位要在第几行后切开数组
)↲ # 一个列表, 其元素为沿着第二维度方向切开后的各 ndarray
np.split(
ndarray_example, # 要拆分的 numpy.ndarray
2, # 若为单个整数则表示均分后的个数(若不能均分则报错), 若为元组则其各元素定位要在指定维度轴的第几个元素后切开数组
axis=0 # 维度轴编号,0为最初维度轴
) # 一个列表, 其元素为沿着指定维度轴方向切开后的各 ndarray
np.array_split(
ndarray_example, # 要拆分的 numpy.ndarray
(3, 4), # 若为单个整数则表示均分后的个数(允许不能均分的整数), 若为元组则其各元素定位要在指定维度方向的第几个元素后切开数组
axis=0 # 维度轴编号, 0 为最初维度轴
)
np.polyfit(
x_i_list, # 自变量坐标列表
y_i_list, # 因变量坐标列表
3 # 多项式次数
) # 最小二乘法多项式拟合的系数 ndarray1-D ndarray
np.poly1d( # 多项式函数生成器
a_list # 要返回的多项式函数的各项系数列表
) # 多项式函数
pip install pandas # Windows 11安装
apt install python3-pandas # Debian 12安装
import numpy as np
import pandas as pd # numpy 是 pandas 的基础
pd.Series( # 用序列创建Series类对象
[1, 'a'],˽ # sequence: Series.values
index=['x', 'y'] # sequence: Series.index; 可选参数默认为自然数序列
)↲ # Series
pd.Series( # 用字典创建Series类对象
{
'a': # Series.index
1, # Seriex.values
'b': #
2
}, # dict
index=['b', 'a'] # sequence: Series.index; 可选参数默认为空
) # Series
pd.DataFrame(
{
'a': # Series.columns
[1, 2], # Seriex.values
'b': #
[3, 4]
}, # dict
index=['a', 'b'] # sequence: DataFrame.index, 可选参数默认为自然数序列
) # 用字典创建的 pandas.DataFrame 类对象
pd.DataFrame(
sequence_eg # sequence: 序列
) # DataFrame: 创建的数据框
pd.read_csv( # 读取文本文件
'./example.csv', # str: 文本文件路径
usecols=['a', 'b'], # 读取指定列
sep=',', # str: 划列分隔符, 可选参数默认为','
head=None, # 可选参数默认无标题行
names=['a', 'b'] # list: 列名, 可选参数默认为文件内容第一行
) # 用文件创建的 pandas.DataFrame 类对象
data_frame_eg.to_csv(
'./example.csv', # 文件路径
columns=['a', 'b'], # 存储指定行
index=False # 不要 index
)
为读取 hdf5 文件安装依赖
pip install tables # hdf5 文件的依赖包
hdf 文件操作
pd.read_hdm( # 读取 hdf5 文件
'.example/example.h5' # 文件路径
)
data_frame_eg.to_hdf(
'example/example.h5', # 文件路径
key='data_frame_eg' # h5 文件中的键
)
pd.read_json(
'example/example.json',
orient='records',
lines='True'
)
data_frame_eg.to_json(
'eg/eg.json',
orient='records',
lines='True' # 分行保存
)
pd.read_excel( # 读取 MS Office Excel 文件的数据
'./example.xlsx' # str: Excel 文件的路径
) # 用文件创建的 pandas.DataFrame 类对象
data_frame_eg.index[2] = 1 # 报错
data_frame_eg.index = [1, 2, 3] # 修改索引值
data_frame_eg.get_indexer()
data_frame_eg.set_index( # 设置索引值
["first", "second"] # str/list: 单个或多个索引值
) # MultiIndex: 设置索引值后的多索引数据框
data_frame_eg.drop(
['a', 'b'], # 维度题
axis=0 # 按哪个维度删除
) # changeobject: DataFrame: 删除数据后的数据框
series_eg.index # pandas.core.indexes.range.RangeIndex 类对象(若为默认自然数索引), 反映索引的起点终点与步长; 或 pandas.core.indexes.base.Index 类对象(若为自定义索引), 反映索引各项及标识符类型
seriex_eg.values # numpy.ndarray 类对象, 为 pandas.Series 中各元素的数组
data_frame_eg.shape # tuple 其元素分别为行数和列数, 即 DataFrame 类对象的 shape
data_frame_eg.columns # 一个列表, 其元素为各列题
data_frame_eg.index # pandas.core.indexes.range.RangeIndex 类对象, 反映索引的起点终点与步长
data_frame_eg.dtypes # 反映每一列的数据类型
data_frame_eg.head(
5 # int: 行数, 可选参数
) # 前几行数据
data_frame_eg.tail(
3 # int: 行数, 可选参数
) # 后几行数据
data_frame_eg.T # 转置
data_frame_describe() # 数据描述
data_frame.column_1 # 指定列题的数据
data_frame.index() # changeobject: 根据索引升序
data_frame_eg.sort_values(
by='abc', # 列题
ascending='True' # bool: True 为升序, False 为降序
) # changeobject: 排序后的数据框
data_frame_eg.sort_values(
by=['a', 'b'], # 先将第一个元素作为列题排序, 若相等则将第二个元素作为列题排序
ascending='False' # bool: True 为升序, False 为降序
) # changeobject: 排序后的数据框
data_series_eg.sort_values(
ascending=True # bool: True 为升序, False 为降序
)
data_seriex_eg.sort.index() # changeobject: 按行引升序排序
data_frame_eg.[
'a' # 列题(column), 不定长参数
] # DataFrame/Series/num
data_frame_eg
.['a' # 列题(column), 不定长参数
][
'b' # 行引(index), 不定长参数
] # DataFrame/Series/num
data_frame_eg.loc[
'a', # 行引(index), 不定长参数
'b':'c' # 列题,同序列切片惯例一样, 但从起点(含)到终点(含)
] # pandas_Series(一列), pandas_DataFrame(多列), 起点到终点
data_frame_eg.iloc[
5:8:2, # 行的数字索引
3 # 列的数字索引
]
import pandas as pd
data_frame_eg.set_index( # 将某一列设为 index
'ymd', # 列题
inplace=Ture # change-object
)
data_frame_eg.groupby() #
data_frame_eg.count() #
pd.isnull() #
pd.notnull() #
pd.qcut() #
pd.cut() #
pd.cosstab( #
value1, #
value2
)
data_frame_eg.pivot_table( #
[], #
index=[]
)
data_frame_eg.dropna() # DataFrame: 删除 NaN 之后的数据框
data_frame_eg.fillna()
data_frame_eg.replace(
'old', #
'new'
) # DataFrame: 替换指定值后的数据框
import pandas as pd
pd.to_datetime(
time_data_series, #
unit='s' # str 时间单位
)
pd.DatatimeIndex()↲
series_eg.add(
10 # 要加的数字
) # 每个元素都加指定的数字
series_eg + 10
series_eg > 10
data_frame_eg.query('column<24 & column>23')
data-frame_eg.isin(['a', 'b'])
data_frame_eg.sum() # 和
data_frame_eg.mean() #
data_frame_eg.median() # 中位数
data_frame_eg.min()
data_frame_eg.max()
data_frame_eg.mode() # 众数
data_frame_eg.abs() # 绝对值
data_frame_eg.prod()
data_frame_eg.std()
data_frame_eg.var()
data_frame_eg.idxmax() # 最大值索引
data_frame_eg.idxmin() # 最小值索引
data_frame_eg.plot(kind=line)
data_frame_eg.cumsum()
data_frame.apply(lambda x: x.max()-x.min(), axis=1) # 自定义运算
四元数相关
pip install numpy-quaternion
import numpy as np # numpy为quaternion的基础依赖
import quaternion # 安装四元数包
import numpy as np
import matplotlib.pyplot as plt
plt.figure( # 设置画布
num=3, # int: 画布编号, 可选参数
figsize=(
8, # int: 画布宽度
5 # int: 画布高度
), # 可选参数
dpi=100, # int: 每英寸像素点数
facecolor='orange' # 背景颜色, 颜色名称或 HEX, 可选参数默认为 white
) # 画布对象
plt.grid() # 设置网格
plt.plot( # 画线
x, # list/tuple/numpy.ndarray: 横轴坐标序列
y, # list/tuple/numpy.ndarray: 纵轴坐标序列
color="red", # str: 线的色名称或HEX, 可选参数默认为 'black'
linewidth=1.0, # float/int: 线宽, 可选参数默认为 1
linestyle="--", # str: 线型, 可选参数默认为 '-'
label='line1' # str: 线名, 可选参数默认为 ''
) # 线对象
plt.plot( # 画折线
x, # 横轴坐标序列
y, # 纵轴坐标序列
'k--', # str: 线色与线型
lw=2.5 # int: 线宽
) # 线对象
plt.scatter( # 画点
x, # 横轴坐标序列
y, # 纵轴坐标序列
s=50, # int: 点径
color='b' # str: 点的颜色名称或HEX
) # 点对象
plt.bar( # 画柱
x, # 横轴坐标序列
y, # 纵轴坐标序列
facecolor='#9999ff', # str: 柱色名或 HEX
edgecolor='white' # str: 框色名或 HEX
) # 柱对象
plt.xlim( # 设置横坐标轴坐标范围
(-1, 2) # 横坐标轴坐标范围
)
plt.ylim( # 设置纵坐标轴坐标范围
(-2, 3) # 纵坐标轴坐标范围
)↲
plt.xticks(
[1, 2, 3] # 横轴刻度
)↲
plt.yticks( # 设置纵轴刻度并将刻度替换成其他文字
[1, 2, 3, 4], # 纵轴刻度
['bad', 'nomal', 'good', 'very good'] # 按纵轴刻度列表对应顺序将纵轴刻度替换成的内容
)
plt.xlable( # 设置横轴标注信息
"I am x" # 横轴标注信息
)↲
plt.ylabel( # 设置横轴标注信息
"I am y" # 纵轴标注信息
)↲
# 写字内容的字符串都可用正则表达式与 LaTeX 数学模式, 格式为: r'正则表达式', $LaTeX数学模式$
plt.annotate( # 对指定点标字
'abc', # 写字内容
xy=(x0, y0), # tuple: 需要指向的目标点的坐标
xycoords='data', #
xytext=(+30, -30), # tuple: 相对于目标点位置坐标的偏移量
fontsize=16, # int: 标注文字大小
arrowprops=dict( # 设置指向目标点的箭头
arrowstyle='->', # str: 箭头样式
connectionstyle='zrc3, rad=.2' # str: 箭头弧度与角度
)
)
plt.text( # 写字
-1, # int/float: 写字位置横坐标
-1, # int/float: 写字位置纵坐标
'This is text', # str: 书写内容
fontdict={
'size':16, # int: 字体大小
'color':'red' # str: 字体颜色
} # dict: 字体设置
)
plt.legend( # 设置图例样式
handles=[
line1, # list: 第 1 个线/点/柱对象
line2 # list: 第 2 个线/点/柱对象
], # list: 需要标注图例的线/点/柱
labels=[
'aaa', # str: 第 1 个线/点/柱对象标注内容
'bbb' # str: 第 2 个线/点/柱对象标注内容
], # list: 按线/点/柱对象的对应顺序列出标注内容
loc='best' # str: 设置图例位置为自动判断最合适的位置
)
plt.gca( # gca 意为 get current axis
).spines[ # 选取指定方位的边框
'right' # str: 边框方位
].setcolor( # 设置边框颜色
'none' # str: 边框颜色
) #
plt.gca().xaixs.set_ticks_position( # 设置横轴 ticks 的位置
'bottom' # str: ticks的位置
)
plt.gca().yaixs.set_ticks_position( # 设置纵轴 ticks 的位置
'left' # str: ticks 的位置
)
plt.gca().spines[
'bottom' # str: 边框方位
].set_position(
(
'data',
0 # int/float: 指定方位的边框经过其垂边的指定点的坐标
)
)
plt.gca().get_xticklabels()[
0 # int: 横轴标数值的索引号
].set_fontsize(
12 # int: 坐标轴数值字体大小
)
plt.gca().get_xticklabels()[
0 # int: 横轴标数值的索引号
].set_bbox( # 设置坐标轴数值方框背景的样式
{
facecolor: 'white', # str: 坐标轴数值背景颜色
edgecolor: 'None', # str: 坐标轴数值方框颜色
alpha: 0.7 # str: 坐标轴数值背景透明度
}
)
plt.show() # 显示图像
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
plt.figure( # 创建画布对象
figsize=(
5, # 画布宽度
3 # 画布高度
) # tuple: 可选参数
) # 画布对象
Axes3D(
figure_eg, # 画布对象
auto_add_to_figure=False # bool, 是否自动添加到画布对象, 可选参数默认为 True
) # 图对象
figure_eg.add_axes(
axes #
) # 将图对象加入到画布对象中
axes.plot( # 画折线
x, # list/tuple/numpy.ndarray: 水平横轴坐标数据序列
y, # list/tuple/numpy.ndarray: 水平纵轴坐标数据序列
z # list/tuple/numpy.ndarray: 竖直轴坐标数据序列
) # 折线对象
axes.scatter( # 画点
x, # list/tuple/numpy.ndarray: 水平横轴坐标数据序列
y, # list/tuple/numpy.ndarray: 水平纵轴坐标数据序列
z, # list/tuple/numpy.ndarray: 竖直轴坐标数据序列
color='red' # str: 点的颜色名称或 HEX
s=100 # str: 点的直径
) # 点对象
axes.bar() # 画柱
plt.show() # 显示图像
import scipy↲
from scipy.optimize import fsolve # 方程求数值解函数
# 参见https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html
def f(x):
return x^2
scipy.optimize.fsolve(
f, # function: 要求解零点的函数
1 # 预估解
) # 函数零点横坐标
def f(
i # list: 含有多个自变量的列表
):
x, y, z = i[0], i[1], i[2] # x1y1 原函数与正比例函数交点, k 正比例函数斜率, x2y3 正比例函数与过原函数极大值点横线的交点
return np.array([
x + y + z,
2*x + y**2 - z,
x**3 + 3*y + z**4,
]) # ndarray: 含有多个因变量的列表
scipy.optimize.fsolve(
f, # function: 要求解零点的函数
[1, 1, 1] # list: 预估解, 解为多个自变量组成的列表
)↲ # ndarray: 多个因变量的共同零点横坐标
scipy.constants.N_A↲ # 阿伏伽德罗常数
scipy.constants.k↲ # 玻尔兹曼常数(J/K)
from scipy.optimize import curve_fit↲ # scipy 包中的最小二乘法多项式拟合函数
from numdifftools import Derivative # 求导功能, 作为 scipy.misc.derivative 弃用后的替代品
# 参见https://numdifftools.readthedocs.io/en/master/tutorials/getting_started.html#the-derivative
Derivative(
function, # 待求导的一元函数, 例如 lambda x: x**2
n=1 # 对其求 1 阶导数
) # 求出的导函数
数学符号式的化简与求解析解
from sympy import Rational # 导入 sympy 包中的 Rational 模块
mathematica 软件的功能, 数学符号式的化简与求解析解