[关闭]
@KarlYan95 2017-07-25T01:23:13.000000Z 字数 8580 阅读 816

NumPy 《Scipy Lecture Notes》

Python


1. Numpy数组对象 The NumPy array object

1.1 什么是NumPy?什么是NumPy数组?

1.1.1 Numpy数组
  1. import numpy as np
  2. a = np.array([0, 1, 2, 3])
  3. a # array([0, 1, 2, 3])
1.1.2 Numpy参考文档
1.1.3 引入Numpy包的习惯写法

1.2 创建数组

1.2.1 手动创建数组
  1. a = np.array([0, 1, 2, 3])
  2. a # array([0, 1, 2, 3])
  3. a.ndim # 1
  4. a.shape # (4,)
  5. len(a) # 4
  1. b = np.array([[0, 1, 2], [3, 4, 5]])# 2 x 3 array
  2. b # array([[0, 1, 2], [3, 4, 5]])
  3. b.ndim # 2
  4. b.shape # (2, 3)
  5. len(b) # 返回第一维的维度 2
  6. c = np.array([[[1], [2]], [[3], [4]]]) # array([[[1], [2]], [[3], [4]]])
  7. c.shape # (2, 2, 1)
1.2.2 创建数组的函数
  1. a = np.arange(10) # 0 .. n-1 (!)
  2. a # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  3. b = np.arange(1, 9, 2) # start, end (exclusive), step
  4. b # array([1, 3, 5, 7])
  1. c = np.linspace(0, 1, 6) # start, end, num-points
  2. c # array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. ])
  3. d = np.linspace(0, 1, 5, endpoint=False)
  4. d # array([ 0. , 0.2, 0.4, 0.6, 0.8])
  1. a = np.ones((3, 3)) # reminder: (3, 3) is a tuple
  2. a
  3. array([[ 1., 1., 1.],
  4. [ 1., 1., 1.],
  5. [ 1., 1., 1.]])
  6. b = np.zeros((2, 2))
  7. b
  8. array([[ 0., 0.],
  9. [ 0., 0.]])
  10. c = np.eye(3)
  11. c
  12. array([[ 1., 0., 0.],
  13. [ 0., 1., 0.],
  14. [ 0., 0., 1.]])
  15. d = np.diag(np.array([1, 2, 3, 4]))
  16. d
  17. array([[1, 0, 0, 0],
  18. [0, 2, 0, 0],
  19. [0, 0, 3, 0],
  20. [0, 0, 0, 4]])
  1. a = np.random.rand(4) # uniform in [0, 1]
  2. a
  3. array([ 0.95799151, 0.14222247, 0.08777354, 0.51887998])
  4. b = np.random.randn(4) # Gaussian
  5. b
  6. array([ 0.37544699, -0.11425369, -0.47616538, 1.79664113])

1.3 基本数据类型

Different data-types allow us to store data more compactly in memory,
but most of the time we simply work with floating point numbers. Note
that, in the example above, NumPy auto-detects the data-type from the
input.
不同的数据类型能够影响数组在内存中存储的紧凑程度,大多数时候,我们只是使用浮点数。
注意,在上面的例子中,NumPy会自动检测数据类型输入。

1.4 基础可视化

  1. import matplotlib.pyplot as plt
  2. plt.plot(x, y)
  3. plt.show()

1.5 索引与切片

  1. a = np.arange(10)
  2. a[5:] = 10
  3. a # array([ 0, 1, 2, 3, 4, 10, 10, 10, 10, 10])
  4. b = np.arange(5)
  5. a[5:] = b[::-1]
  6. a # array([0, 1, 2, 3, 4, 4, 3, 2, 1, 0])

索引与切片

1.6 拷贝与视图

A slicing operation creates a view on the original array, which is
just a way of accessing array data. Thus the original array is not
copied in memory. You can use np.may_share_memory() to check if # two
arrays share the same memory block. Note however, that this uses
heuristics and may give you false positives.
切片操作的结果,仅仅是在原数组上产生一个视图,以此达到访问数据的目的。因此,原始数组并没有被拷贝到内存中,可以使用np.may_share_memory()来查看两个数组是否共享内存。注意,这里使用了启发式方法,可能会有误报。

1.7 花式索引 Fancy indexing

NumPy arrays can be indexed with slices, but also with boolean or
integer arrays (masks). This method is called fancy indexing. It
creates copies not views.
NumPy数组可以通过切片索引,也可以使用布尔值或整数数组(掩码)进行索引。这种方法叫做花式索引。 它创建的是副本而非视图。

1.7.1 使用bool掩码
  1. # 通过花式索引,切片得到仅包含3的倍数的新数组
  2. np.random.seed(3)
  3. a = np.random.random_integers(0, 20, 15)
  4. a # array([10, 3, 8, 0, 19, 10, 11, 9, 10, 6, 0, 20, 12, 7, 14])
  5. b = (a % 3 == 0) # 得到一个与a一样长的bool数组。在相同的索引位置i上,若a[i]为3的倍数,则b[i]为True,否则为False
  6. extract_from_a = a[mask] # array([ 3, 0, 9, 6, 0, 12])
  7. a[a % 3 == 0] = -1 # 3的倍数都被赋值为-1
1.7.2 使用整数数组的花式索引
  1. a = np.arange(0, 100, 10) # 创建一个数组 a
  2. # 索引可以是也一个整数数组,相同的索引可以重复
  3. a[[2, 3, 2, 4, 2]] # array([20, 30, 20, 40, 20])
  4. # 也可以通过以下方式进行赋值
  5. a[[9, 7]] = -100 # array([0,10,20,30,40,50,60,-100,80,-100])
  6. # 当通过整数数组花式索引index创建一个新数组时,新数组与index形状相同
  7. a = np.arange(10)
  8. index = np.array([[3, 4], [9, 7]]) # index.shape = (2, 2)
  9. a[index] # array([[3, 4],[9, 7]])

花式索引

2. 数组数值运算 Numerical operations on arrays

2.1 智慧数组操作 Elementwise operations

2.1.1 基本操作

可进行基本的+-*/操作

  1. a = np.array([1, 2, 3, 4])
  2. b = np.ones(4) + 1
  3. a + 1 # 每个元素+1
  4. 2**a# 每个元素平方
  5. a - b # 每个元素相减
  6. a * b # 每个元素相乘
  7. j = np.arange(5)
  8. 2**(j + 1) - j # 批量操作
  9. # 数组间的乘法为c.dot(c)
2.1.2 其他操作
数组的比较
  1. a = np.array([1, 2, 3, 4])
  2. b = np.array([4, 2, 2, 4])
  3. a == b
  4. a > b # 逐元素比较,返回一个bool数组
数组整体进行比较
  1. a = np.array([1, 2, 3, 4])
  2. b = np.array([4, 2, 2, 4])
  3. c = np.array([1, 2, 3, 4])
  4. np.array_equal(a, b)
  5. np.array_equal(a, c) # 整个数组进行比较返回bool值
逻辑操作(Logical operations)
  1. a = np.array([1, 1, 0, 0], dtype=bool)
  2. b = np.array([1, 0, 1, 0] dtype=bool)
  3. np.logical_or(a, b)
  4. np.logical_and(a, b)
超越函数(Transcendental Functions)

指变量之间的关系不能用有限次加、减、乘、除、乘方、开方运算表示的函数。

  1. a = np.arange(5)
  2. np.sin(a)
  3. np.log(a)
  4. np.exp(a)
矩阵逆置(Transposition)
  1. a = np.triu(np.ones((3, 3)), 1) # 上三角行列式 np.tril下三角行列式
  2. a.T

2.2 数组/矩阵的基础约简 Basic reductions

2.2.1 计算元素之和
数组
  1. x = np.array([1, 2, 3, 4])
  2. np.sum(x)
  3. x.sum() # 均返回数组元素之和
按行/列求和
  1. x = np.array([[1, 1], [2, 2]])
  2. x.sum(axis=0) # 列求和,1维求和
  3. x[:, 0].sum(), x[:, 1].sum()
  4. x.sum(axis=1) # 行求和,第2维求和
  5. x[0, :].sum(), x[1, :].sum()
2.2.2 其它约简
极值
  1. x = np.array([1, 3, 2])
  2. x.min()
  3. x.max()
  4. x.argmin() # 返回最小值索引
  5. x.argmax() # 返回最大值索引
逻辑运算
  1. np.all([True, True, False]) # False
  2. np.any([True, True, False]) # True
统计运算
  1. x = np.array([1, 2, 3, 1])
  2. y = np.array([[1, 2, 3], [5, 6, 1]])
  3. x.mean() # 均值
  4. np.median(x) # 中位数
  5. np.median(y, axis=-1) # last axis array([ 2., 5.])
  6. x.std() # 标准差

2.3 广播 Broadcasting

It’s also possible to do operations on arrays of different sizes if
NumPy can transform these arrays so that they all have the same size:
this conversion is called broadcasting.
若通过Numpy能将不同形状的数组/矩阵转换为相同形状,则这些数组/矩阵之间可以进行运算。

Broadcasting

一个常用的技巧
  1. a = np.arange(0, 40, 10)
  2. a.shape
  3. (4,)
  4. a = a[:, np.newaxis] # adds a new axis -> 2D array
  5. a.shape
  6. (4, 1)
  7. a
  8. array([[ 0],
  9. [10],
  10. [20],
  11. [30]])
  12. a + b
  13. array([[ 0, 1, 2],
  14. [10, 11, 12],
  15. [20, 21, 22],
  16. [30, 31, 32]])
np.ogrid
  1. x, y = np.ogrid[0:5, 0:5]
  2. x, y
  3. (array([[0],
  4. [1],
  5. [2],
  6. [3],
  7. [4]]), array([[0, 1, 2, 3, 4]]))
  8. x.shape, y.shape
  9. ((5, 1), (1, 5))
  10. distance = np.sqrt(x ** 2 + y ** 2)
np.mgrid
  1. x, y = np.mgrid[0:4, 0:4]
  2. x
  3. array([[0, 0, 0, 0],
  4. [1, 1, 1, 1],
  5. [2, 2, 2, 2],
  6. [3, 3, 3, 3]])
  7. y
  8. array([[0, 1, 2, 3],
  9. [0, 1, 2, 3],
  10. [0, 1, 2, 3],
  11. [0, 1, 2, 3]])

2.4 改变数组形状 Array shape manipulation

2.4.1 扁平化 Flattening

np.ravel()

  1. a = np.array([[1, 2, 3], [4, 5, 6]])
  2. a.ravel()
  3. array([1, 2, 3, 4, 5, 6])
  4. a.T
  5. array([[1, 4],
  6. [2, 5],
  7. [3, 6]])
  8. a.T.ravel()
  9. array([1, 4, 2, 5, 3, 6])
2.4.2 重塑 Reshaping

Flatting 的逆函数
np.reshape(shape)

2.4.3 升维 Adding a dimension
  1. L = np.arange(0, 3) # shape: (3, )
  2. x = L[:, np.newaxis] # shape: (3, 1)
  3. y = L[np.newaxis, :] # shape: (1, 3)
2.4.4 维度洗牌 Dimension Shuffling
  1. np.transpose() # i与n-i交换维度
2.4.5 重新定义大小 Resizing
  1. np.resize(shape) 注:被resize的数组不能被赋给其他数组

2.5 数据的排序 Sorting data

  1. np.sort(self, asix= )

2.6 总结 Summary


3. 更复杂的数组 More elaborate arrays

3.1 更多数据类型 More data types

3.1.1 强制转型 Casting
  1. np.array([1, 2, 3]) + 1.5
  2. array([ 2.5, 3.5, 4.5]) # int ---> float
  1. a = np.array([1, 2, 3])
  2. a.dtype # dtype('int64')
  3. a[0] = 1.9 # <-- float is truncated to integer
  4. a # array([1, 2, 3])
  1. a = np.array([1.7, 1.2, 1.6])
  2. b = a.astype(int) # b = array([1, 1, 1]
  1. a = np.array([1.2, 1.5, 1.6, 2.5, 3.5, 4.5])
  2. b = np.around(a) # array([ 1., 2., 2., 2., 4., 4.])
3.1.2 不同数据类型的大小 Different data type sizes
  1. # 在进行数据运算时,越小的数据类型,速度越快;其所占的空间的要求的宽度也越小
  2. int8/uint8 # 8 bits
  3. int16/uint16/float16 # 16 bits
  4. int32/uint32/float32 # 32 bits
  5. int64/uint64/float64 # 64 bits
  6. float128 # 128 bits, 取决于平台
  7. complex64 # two 32-bit floats
  8. complex128 # two 64-bit floats
  9. complex192 # two 96-bit floats, 取决于平台
  10. complex256 # two 128-bit floats, 取决于平台

3.2 结构化数据类型 Structured data types

  1. # 示例
  2. # sensor_code (4-character string)
  3. # position (float)
  4. # value (float)
  5. samples = np.zeros((6,), dtype=[('sensor_code', 'S4'), ('position', float), ('value', float)])
  6. samples.ndim # 1
  7. samples.shape # (6,)
  8. samples.dtype.names # ('sensor_code', 'position', 'value')

3.3 maskedarray:处理丢失的数据

  1. x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])
  2. x
  3. masked_array(data = [1 -- 3 --],
  4. mask = [False True False True],
  5. fill_value = 999999)
  6. y = np.ma.array([1, 2, 3, 4], mask=[0, 1, 1, 1])
  7. x + y
  8. masked_array(data = [2 -- -- --],
  9. mask = [False True True True],
  10. fill_value = 999999)
  1. np.ma.sqrt([1, -1, 2, -2])
  2. masked_array(data = [1.0 -- 1.41421356237... --],
  3. mask = [False True False True],
  4. fill_value = 1e+20)

4. 高级运算

4.1 多项式 Polynomials

  1. p = np.poly1d([3, 2, -1])
  2. p(0) # -1, x=0时y的值
  3. p.roots # array([-1., 0.33333333]),顶点
  4. p.order # 2, 次数
4.1.1 更多的多项式(更高次数) More polynomials (with more bases)


4.2 载入数据文件

4.2.1 文本文件
4.2.2 图片
  1. img = plt.imread('data/elephant.png')
  2. img.shape, img.dtype # ((200, 300, 3), dtype('float32'))
  3. plt.imshow(img)
  4. <matplotlib.image.AxesImage object at ...>
  5. plt.savefig('plot.png')
  6. plt.imsave('red_elephant', img[:,:,0], cmap=plt.cm.gray)
4.2.3 NumPy的自有格式
  1. data = np.ones((3, 3))
  2. np.save('pop.npy', data)
  3. data3 = np.load('pop.npy')
4.2.4 知名的文件格式


心血来潮,自娱自乐,供自己参考=.=
mr.yxj@foxmail.com

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注