CS172 计算机编程II笔记
211008
numpy
array
与list不同,支持数学运算
1 | a = [1,2,3,4] |
支持切片,支持逐项运算
1 | a[:2] + a[-2:] # [4 6] |
1 | a.shape # (4,) 形状,可以得到数组维度和每一维大小, 等价shape(a) |
索引
a[x, y]:二维索引,支持切片
切片是引用,即同地址,改变值时会全部改变,可以用.copy()生成新的备份
arange(start(close), end(open), step): array-range
a[rows=(x1, x2, ...)[, cols=(y1, y2, ...)]]:分行列
a > 10: 返回dtype=bool的mask数组
where(a > 10):返回mask为True的index
类型
a.dtype:data_type, 可以指定
complex: a.conj()求共轭,a.imag可以修改虚部值(仅限dtype=complex),
a.nbytes: 查看所用字节
a.tofile('filename'): 保存到文件
frombuffer('buf')
a.dtype=object:任意类型array
asarray(src, dtype=type): 类型转换,类型相同则返回引用
a.astype(type):返回新的数组(copy)
画图
linspace
生成等间隔的数据,linspace(a,b,c)表示$[a,b]$分为$c$个点,相邻点间等距。
plot
matlabplot->plot(a, b, ...)画图,inline嵌入。
mask = condition可以做条件筛选,plot(a[mask], b[mask], 'ro')画出条件部分,ro表示红色圆点。
导入:import matplotlib as plt
plot(y):默认x轴为索引
plot(x, y):平面双轴
plot(x, y, format_string):平面双轴,自定义格式
format_string:
-: line--: dash line^: triangle nodehelp(plot)for more
scatter 散点图
figure(): 生成图, colorbar(), subplot(), hold(False): 保持,不保持则直接覆盖,不叠加在前一张图上, plot(..., label=""), label=[], xlabel('', fontsize=), ylabel('', fontsize=), legend(): 显示label, grid(): 显示网格
关闭图像
clf(), close(), close('all')
imshow 显示图像
1 | from PIL import Image |