李金的中文Python笔记[https://github.com/lijin-thu/notes-python]的学习笔记及摘要。
matplotlib包
scatter 散点图
scatter(x, y)
scatter(x, y, size)
scatter(x, y, size, color)
subplot
在一幅图中画多幅子图
subplot(row, column, index)
subplot(1, 2, 1)
plot(x)
subplot(1, 2, 2)
plot(y)
清除、关闭图像
清除已有的图像使用:clf()
关闭当前图像:close()
关闭所有图像:close('all')
numpy数组
数组属性
from numpy import *
a = array([1, 2, 3, 4])
- 查看类型:
type(a)
——output:numpy.ndarray
- 查看数组中的数据类型:
a.dtype
——output:dtype('int32')
numpy array 切片是引用
a = array([0,1,2,3,4])
b = a[2:4]
print b
- 引用机制意味着,Python并没有为
b
分配新的空间来存储它的值,而是让b
指向了a
所分配的内存空间,因此,改变b
会改变a
的值。 - 这样做的好处在于,对于很大的数组,不用大量复制多余的值,节约了空间。缺点在于,可能出现改变一个值改变另一个值的情况。
- 一个解决方法是使用copy()方法产生一个复制,这个复制会申请新的内存:
a = array([0,1,2,3,4])
b = a[2:4].copy()
b[0] = 10
a
一维花式索引
a = arange(0, 80, 10)
a
> array([ 0, 10, 20, 30, 40, 50, 60, 70])
还可以使用布尔数组来花式索引:
mask = array([0,1,1,0,0,1,0,0],
dtype=bool)
a[mask]
> array([10, 20, 50])
或者用布尔表达式生成 mask(必须是布尔数组),选出了所有大于0.5的值:
from numpy.random import rand
a = rand(10)
a
> array([0.08225093, 0.65431312, 0.76956763, 0.22992887, 0.26223611,
0.18102709, 0.59408112, 0.63500126, 0.34168543, 0.82241556])
mask = a > 0.5
a[mask]
> array([ 0.73365131, 0.62068734, 0.53085308])
与切片不同,花式索引返回的是原对象的一个复制而不是引用。
where语句
where
函数会返回所有非零元素的索引。注意到 where 的返回值是一个元组。
所以使用时可以如下方法:
indices = where(a>10)[0]
indices
% 或者如下:直接用 where 的返回值进行索引
loc = where(a > 10)
a[loc]
Numpy 类型
具体如下:
基本类型 | 可用的Numpy类型 | 备注 |
---|---|---|
布尔型 | bool | 占1个字节 |
整型 | int8, int16, int32, int64, int128, int | int 跟C语言中的 long 一样大 |
无符号整型 | uint8, uint16, uint32, uint64, uint128, uint | uint 跟C语言中的 unsigned long 一样大 |
浮点数 | float16, float32, float64, float, longfloat | 默认为双精度 float64 ,longfloat 精度大小与系统有关 |
复数 | complex64, complex128, complex, longcomplex | 默认为 complex128 ,即实部虚部都为双精度 |
字符串 | string, unicode | 可以使用 dtype=S4 表示一个4字节字符串的数组 |
对象 | object | 数组中可以使用任意值 |
Records | void | |
时间 | datetime64, timedelta64 |
数组形状
使用 newaxis 增加数组维数
a = arange(3)
shape(a)
> (3,)
y = a[newaxis, newaxis, :]
shape(y)
> (1, 1, 3)
squeeze 方法去除多余的轴
squeeze 返回一个将所有长度为1的维度去除的新数组。
a = arange(6)
a.shape = (2,1,3)
b = a.squeeze()
b.shape
> (2, 3)
Flatten 数组:将多维数组转化为1维数组
a = array([[0,1],
[2,3]])
b = a.flatten()
b
> array([0, 1, 2, 3])
数组属性方法总结
作用 | |
---|---|
1 | 基本属性 |
a.dtype | 数组元素类型 float32,uint8,... |
a.shape | 数组形状 (m,n,o,...) |
a.size | 数组元素数 |
a.itemsize | 每个元素占字节数 |
a.nbytes | 所有元素占的字节 |
a.ndim | 数组维度 |
2 | 形状相关 |
a.flat | 所有元素的迭代器 |
a.flatten() | 返回一个1维数组的复制 |
a.ravel() | 返回一个1维数组,高效 |
a.resize(new_size) | 改变形状 |
a.swapaxes(axis1, axis2) | 交换两个维度的位置 |
a.transpose(*axes) | 交换所有维度的位置 |
a.T | 转置,a.transpose() |
a.squeeze() | 去除所有长度为1的维度 |
3 | 填充复制 |
a.copy() | 返回数组的一个复制 |
a.fill(value) | 将数组的元组设置为特定值 |
4 | 转化 |
a.tolist() | 将数组转化为列表 |
a.tostring() | 转换为字符串 |
a.astype(dtype) | 转化为指定类型 |
a.byteswap(False) | 转换大小字节序 |
a.view(type_or_dtype) | 生成一个使用相同内存,但使用不同的表示方法的数组 |
5 | 复数 |
a.imag | 虚部 |
a.real | 实部 |
a.conjugate() | 复共轭 |
a.conj() | 复共轭(缩写) |
6 | 保存 |
a.dump(file) | 将二进制数据存在file中 |
a.dump() | 将二进制数据表示成字符串 |
a.tofile(fid, sep="",format="%s") | 格式化ASCⅡ码写入文件 |
7 | 查找排序 |
a.nonzero() | 返回所有非零元素的索引 |
a.sort(axis=-1) | 沿某个轴排序 |
a.argsort(axis=-1) | 沿某个轴,返回按排序的索引 |
a.searchsorted(b) | 返回将b中元素插入a后能保持有序的索引值 |
8 | 元素数学操作 |
a.clip(low, high) | 将数值限制在一定范围内 |
a.round(decimals=0) | 近似到指定精度 |
a.cumsum(axis=None) | 累加和 |
a.cumprod(axis=None) | 累乘积 |
9 | 约简操作 |
a.sum(axis=None) | 求和 |
a.prod(axis=None) | 求积 |
a.min(axis=None) | 最小值 |
a.max(axis=None) | 最大值 |
a.argmin(axis=None) | 最小值索引 |
a.argmax(axis=None) | 最大值索引 |
a.ptp(axis=None) | 最大值减最小值 |
a.mean(axis=None) | 平均值 |
a.std(axis=None) | 标准差 |
a.var(axis=None) | 方差 |
a.any(axis=None) | 只要有一个不为0,返回真,逻辑或 |
a.all(axis=None) | 所有都不为0,返回真,逻辑与 |
生成数组的函数
arange
arange
类似于Python中的 range
函数,只不过返回的不是列表,而是数组:
arange(start, stop=None, step=1, dtype=None)
产生一个在区间 [start, stop)
之间,以 step
为间隔的数组,如果只输入一个参数,则默认从 0
开始,并以这个值为结束。
linspace
linspace(start, stop, N)
产生 N
个等距分布在 [start, stop]
间的元素组成的数组,包括 start, stop
。
logspace
logspace(start, stop, N)
产生 N
个对数等距分布的数组,默认以10
为底。
np.logspace(0, 1, 5)
> array([ 1. , 1.77827941, 3.16227766, 5.62341325, 10. ])
产生的值为 [ 1 0 0 , 1 0 0.25 , 1 0 0.5 , 1 0 0.75 , 1 0 1 ] \left[10^0, 10^{0.25},10^{0.5},10^{0.75},10^1\right] [100,100.25,100.5,100.75,101]。
empty
empty(shape, dtype=float64, order='C')
也可以使用 empty
方法产生一个制定大小的数组(数组所指向的内存未被初始化,所以值随机),再用 fill
方法填充:
empty_like, ones_like, zeros_like
empty_like(a)
ones_like(a)
zeros_like(a)
产生一个跟 a
大小一样,类型一样的对应数组。
identity
indentity(n, dtype=float64)
产生一个 n
乘 n
的单位矩阵:
np.identity(3)
> array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
数组广播机制
Numpy根据两者的维度,自动将它们进行扩展然后进行计算。
对于 Numpy 来说,维度匹配当且仅当:
- 维度相同
- 有一个的维度是1
匹配会从最后一维开始进行,直到某一个的维度全部匹配为止,因此对于以下情况,Numpy 都会进行相应的匹配:
A | B | Result |
---|---|---|
3d array: 256 x 256 x 3 | 1d array: 3 | 3d array: 256 x 256 x 3 |
4d array: 8 x 1 x 6 x 1 | 3d array: 7 x 1 x 5 | 3d array: 8 x 7 x 6 x 5 |
3d array: 5 x 4 x 3 | 1d array: 1 | 3d array: 5 x 4 x 3 |
3d array: 15 x 4 x 13 | 1d array: 15 x 1 x 13 | 3d array: 15 x 4 x 13 |
2d array: 4 x 1 | 1d array: 3 | 2d array: 4 x 3 |
匹配成功后,Numpy 会进行运算得到相应的结果。
数组读写
loadtxt 函数
loadtxt(fname, dtype=<type 'float'>,
comments='#', delimiter=None,
converters=None, skiprows=0,
usecols=None, unpack=False, ndmin=0)
loadtxt
有很多可选参数,其中 delimiter
就是刚才用到的分隔符参数。
skiprows
参数表示忽略开头的行数,可以用来读写含有标题的文本。
例如:
%%writefile myfile.txt
-- BEGINNING OF THE FILE
% Day, Month, Year, Skip, Power
01, 01, 2000, x876, 13 % wow!
% we don't want have Jan 03rd
04, 01, 2000, xfed, 55
data = np.loadtxt('myfile.txt',
skiprows=1, #忽略第一行
dtype=np.int, #数组类型
delimiter=',', #逗号分割
usecols=(0,1,2,4), #指定使用哪几列数据
comments='%' #百分号为注释符
)
data
> array([[ 1, 1, 2000, 13],
[ 4, 1, 2000, 55]])
loadtxt 自定义转换方法
%%writefile myfile.txt
2010-01-01 2.3 3.2
2011-01-01 6.1 3.1
假设我们的文本包含日期,我们可以使用 datetime
在 loadtxt
中处理:
import datetime
def date_converter(s):
return datetime.datetime.strptime(s, "%Y-%m-%d")
data = np.loadtxt('myfile.txt',
dtype=np.object, #数据类型为对象
converters={0:date_converter, #第一列使用自定义转换方法
1:float, #第二第三使用浮点数转换
2:float})
data
> array([[datetime.datetime(2010, 1, 1, 0, 0), 2.3, 3.2],
[datetime.datetime(2011, 1, 1, 0, 0), 6.1, 3.1]], dtype=object)
读写各种格式的文件
如下表所示:
文件格式 | 使用的包 | 函数 |
---|---|---|
txt | numpy | loadtxt, genfromtxt, fromfile, savetxt, tofile |
csv | csv | reader, writer |
Matlab | scipy.io | loadmat, savemat |
hdf | pytables, h5py | |
NetCDF | netCDF4, scipy.io.netcdf | netCDF4.Dataset, scipy.io.netcdf.netcdf_file |
文件格式 | 使用的包 | 备注 |
wav | scipy.io.wavfile | 音频文件 |
jpeg,png,… | PIL, scipy.misc.pilutil | 图像文件 |
fits | pyfits | 天文图像 |
此外, pandas
——一个用来处理时间序列的包中包含处理各种文件的方法,具体可参见它的文档:
http://pandas.pydata.org/pandas-docs/stable/io.html
将数组写入文件
savetxt
可以将数组写入文件,默认使用科学计数法的形式保存:
savetxt(fname,
X,
fmt='%.18e', #数组的保存格式,如"%.2f",2位小数的浮点数
delimiter=' ',
newline='\n',
header='',
footer='',
comments='# ')
结构化数组 3.20-structured-arrays
待学习