【Python入门】Numpy扩展程序库常用函数

NumPy(Numerical Python) 是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,也针对数组运算提供大量的数学函数库。通常与 SciPy(Scientific Python)和 Matplotlib(绘图库)一起使用。NumPy 官网 http://www.numpy.org/

推荐工具:Jupyter Notebook (非常推荐!一个基于Web的交互式应用程序)

内容来源:RUNOOB.COM

1. NdArray对象

NumPy的重要特性是N维数组对象ndarray,存放同类型数据的多维数组。

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
## NumPy最重要的特点:N维数组对象ndarray
## numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
a = np.array([1,2,3])
print(a) # 一维
b = np.array([[1,2],[3,4]])
print(b) # 二维
c = np.array([1,2,3,4,5], ndmin = 2)
print(c) # 指定生成数组的最小维度
d = np.array([1,3,5,7], dtype = complex)
print(d) # 数组元素的数据类型
[1 2 3]
[[1 2]
 [3 4]]
[[1 2 3 4 5]]
[1.+0.j 3.+0.j 5.+0.j 7.+0.j]

2. dtype对象和实例应用

numpy.dtype(object, align, copy)
## 数据类型对象
## numpy.dtype(object, align, copy)
dt1 = np.dtype(np.int32)
print(dt1)
dt2 = np.dtype('<i4')
print(dt2)
dt3 = np.dtype([('age',np.int8)]) # 定义结构化的数据类(一个字段)
print(dt3)
x = np.array([(10,),(20,),(30,)],dtype = dt3) # dt3的实例
print(x)
print(x['age'])

person = np.dtype([('name','S20'),('job','S12'),('age','i4')])
print(person) #  # 定义结构化的数据类(3个字段)
list = np.array([('zhangsan','student',20),('lisi','teacher',50)],dtype = person) # person的实例,注意标注dtype
print(list)
print(list['name'])
int32
int32
[('age', 'i1')]
[(10,) (20,) (30,)]
[10 20 30]
[('name', 'S20'), ('job', 'S12'), ('age', '<i4')]
[(b'zhangsan', b'student', 20) (b'lisi', b'teacher', 50)]
[b'zhangsan' b'lisi']

 3. NumPy数组的属性

## NumPy数组属性
a = np.arange(1,13,2) # 创建等差数组
print(a,a.shape,a.ndim,a.size) # ndarry的维度、秩、元素总个数
b = a.reshape(2,3)  # 调整数组大小
print(b,b.shape,b.ndim)
b.shape = (3,2) # 调整数组大小
print(b,b.shape,b.ndim)
x = np.array([1,2,3,4,5],dtype = np.int8)
print(x.itemsize) # 以字节(byte)的形式返回ndarray每个元素的大小
y = np.array([5,4,3,2],dtype = np.float64)
print(y.itemsize)
print(b.flags) # ndarray 对象的内存信息
[ 1  3  5  7  9 11] (6,) 1 6
[[ 1  3  5]
 [ 7  9 11]] (2, 3) 2
[[ 1  3]
 [ 5  7]
 [ 9 11]] (3, 2) 2
1
8
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

4. NumPy创建数组

numpy.empty(shape, dtype = float, order = 'C')
numpy.zeros(shape, dtype = float, order = 'C')
numpy.ones(shape, dtype = None, order = 'C')
## NumPy创建数组
x = np.empty([3,1],dtype = float, order = 'C') # 创建空数组,C/F表示行优先、列优先
print(x)
y = np.zeros([2,4],dtype = int) #创建指定大小的数组,数组元素以 0 来填充
print(y)
z = np.ones([2,2]) # 创建指定形状的数组,数组元素以 1 来填充(默认float)
print(z)
a = np.random.randn(2,3) # 创建标准正态分布数组
print(a)
b = np.eye(4,dtype=int) # 创建对角矩阵数组
print(b)
[[6.36598737e-314]
 [1.48539705e-313]
 [2.33419537e-313]]
[[0 0 0 0]
 [0 0 0 0]]
[[1. 1.]
 [1. 1.]]
[[-0.52420196  1.1293313   1.86596517]
 [-2.26587893  0.10869122  0.70468794]]
[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]

5. NumPy从已有的数组(列表、元组等,Buffer、迭代器)创建数组

numpy.asarray(a, dtype = None, order = None)
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
numpy.fromiter(iterable, dtype, count=-1)
## NumPy从已有的数组创建数组
## numpy.asarray(a, dtype = None, order = None)
## 任意形式的输入参数,可以是,列表, 列表的元组, 元组, 元组的元组, 元组的列表,多维数组
x = [1,2,3] ##列表
a = np.asarray(x)
print(a)
x = (4,5,6) ##元组
a = np.asarray(x)
print(a)
x = [(1,2,3),(4,5)] ## 元组的列表
a = np.asarray(x)
print(a)
x = [1,2,3]
a = np.asarray(x,dtype = float)
print(a)
## numpy.frombuffer 用于实现动态数组。numpy.frombuffer 接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象。
## numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
s = b'python language' # 注意:buffer是字符串时,Python3默认str是Unicode类型,所以要转成bytestring在原str前加上b。
a = np.frombuffer(s,dtype = 'S1')
print(a)
## numpy.fromiter 方法从可迭代对象中建立 ndarray 对象,返回一维数组。
## numpy.fromiter(iterable, dtype, count=-1)
list = range(6) # 列表对象
it = iter(list)
x = np.fromiter(it,dtype = 'i4') ## 使用迭代器,创建ndarray
print(x)
[1 2 3]
[4 5 6]
[(1, 2, 3) (4, 5)]
[1. 2. 3.]
[b'p' b'y' b't' b'h' b'o' b'n' b' ' b'l' b'a' b'n' b'g' b'u' b'a' b'g'
 b'e']
[0 1 2 3 4 5]

6. NumPy 从数值范围创建数组

numpy.arange(start, stop, step, dtype)
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
## NumPy 从数值范围创建数组
a = np.arange(1,17,3) 
print(a) #根据start与stop指定的范围以及step设定的步长,生成一个等差数组
b = np.linspace(10,40,4) 
print(b) #根据start与stop指定的范围以及num设定的样本数量,生成一个等差数组
c = np.logspace(1.0,2.0,num = 10)
print(c) #起始值为base*start,终止值为base*stop(base默认为10),个数为10的等比数组
d = np.logspace(0,9,10,base=2)
print(d) #自定义底数base=2
[ 1  4  7 10 13 16]
[10. 20. 30. 40.]
[ 10.          12.91549665  16.68100537  21.5443469   27.82559402
  35.93813664  46.41588834  59.94842503  77.42636827 100.        ]
[  1.   2.   4.   8.  16.  32.  64. 128. 256. 512.]

7. NumPy的索引和切片

和Python内置list的索引和切片基本一致。

## NumPy切片和索引
a = np.arange(10)
s = slice(1,9,2) # 索引从1到9,间隔为2
print(a[s])
b = a[2:9:3] # 索引从2到9,间隔为3
print(b)
c = a[2:] # 该索引开始以后的所有项都将被提取
print(c)
print(a[2:7]) #提取两个索引(不包括停止索引)之间的项

x = np.array([[1,2,3],[4,5,6],[7,8,9]]) #多维数组
print(x)
print(x[1:]) # 从索引1处开始切割
print(x[...,1]) # 第2列(索引1)元素
print(x[1,...]) # 第2行元素
print(x[...,1:]) # 第2列以后的元素
[1 3 5 7]
[2 5 8]
[2 3 4 5 6 7 8 9]
[2 3 4 5 6]
[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[4 5 6]
 [7 8 9]]
[2 5 8]
[4 5 6]
[[2 3]
 [5 6]
 [8 9]]

8. NumPy高级索引

NumPy 比一般的 Python 序列提供更多的索引方式。除了用整数和切片的索引外,数组可以由整数数组索引、布尔索引及花式索引。分为整数数组索引、布尔索引、花式索引。

## NumPy高级索引
# 整数数组索引
x = np.array([['a','b','c'],['c','d','e'],['e','f','g']],dtype='S4')
print(x)
print(x[[0,1,2],[0,1,0]]) # 获取数组中(0,0),(1,1)和(2,0)位置处的元素。
rows = np.array([[0,0],[2,2]])
cols = np.array([[0,2],[0,2]])
print(x[rows,cols]) # 获取数组4个角的元素
print(x[0:3,[1,2]]) # 第1-3行,第2、3列
print(x[1:,...]) # 第2行及其以后
# 布尔索引
x = np.array([[9,8,7],[6,5,4],[3,2,1]])
print(x[x>4]) # 大于 4 的元素
y = np.array([np.nan,1,2,np.nan,3,4])
print(y[~np.isnan(y)]) # 过滤掉NaN
z = np.array([[1+2j,3],[3+4j,5+1j],[3+4j,0]])
print(z[np.iscomplex(z)]) # 只保留复数
# 花式索引:利用整数数组进行索引
# 花式索引跟切片不一样,它总是将数据复制到新数组中。
x = np.arange(32).reshape(8,4) # 二维数组
print(x)
print(x[[4,2,1,7]]) # 传入顺序索引数组
print(x[[-4,-2,-1,-7]]) # 传入倒序索引数组
print(x[np.ix_([1,5,7,2],[0,3,1,2])]) # 传入多个索引数组
[[b'a' b'b' b'c']
 [b'c' b'd' b'e']
 [b'e' b'f' b'g']]
[b'a' b'd' b'e']
[[b'a' b'c']
 [b'e' b'g']]
[[b'b' b'c']
 [b'd' b'e']
 [b'f' b'g']]
[[b'c' b'd' b'e']
 [b'e' b'f' b'g']]
[9 8 7 6 5]
[1. 2. 3. 4.]
[1.+2.j 3.+4.j 5.+1.j 3.+4.j]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]
 [24 25 26 27]
 [28 29 30 31]]
[[16 17 18 19]
 [ 8  9 10 11]
 [ 4  5  6  7]
 [28 29 30 31]]
[[16 17 18 19]
 [24 25 26 27]
 [28 29 30 31]
 [ 4  5  6  7]]
[[ 4  7  5  6]
 [20 23 21 22]
 [28 31 29 30]
 [ 8 11  9 10]]

9. NumPy广播(Broadcast)

NumPy对不同形状(shape)的数组进行数值计算的方式。详见广播规则

## NumPy广播(Broadcast)
# 广播规则
a = np.array([1,2,3])
b = np.array([1,10,100])
print(a*b)
c = np.array([[0,0,0],[10,10,10],[100,100,100],[1000,1000,1000]])
print(b+c) # 维度不同,自动触发广播机制
bb = np.tile(b,(4,1)) # tile函数重复b的各个维度
print(bb+c)
[  1  20 300]
[[   1   10  100]
 [  11   20  110]
 [ 101  110  200]
 [1001 1010 1100]]
[[   1   10  100]
 [  11   20  110]
 [ 101  110  200]
 [1001 1010 1100]]

10. NumPy迭代数组

NumPy 迭代器对象 numpy.nditer 提供了一种灵活访问一个或者多个数组元素的方式。

## NumPy 迭代数组
a = np.arange(6).reshape(2,3)
print(a)
for x in np.nditer(a):
    print(x,end=',') # 默认按照行优先访问(C风格)
print('\n')
for x in np.nditer(a,order='F'):
    print(x,end=',') # 显式说明,按照列优先访问(Fortran风格)
print('\n')
for x in np.nditer(a.T): 
    print(x,end=',') # a和a.T的遍历顺序一样,是因为它们在内存中存储顺序一样
print('\n')
b = a.T.copy(order='C')
for x in np.nditer(b):
    print(x,end=',') # 和上述不一样,是因为和前两种的存储方式是不一样的,默认是按行访问。
print('\n')
# 迭代过程修改元素的值
a = np.arange(0,60,5).reshape(3,4)
print(a)
for x in np.nditer(a,op_flags=['readwrite']): # nditer类的构造器有op_flags参数
    x[...]=2*x # 默认是read-only的,对数组元素值修改,必须指定 read-write 或者 write-only 的模式。
print(a)
# 使用外部循环
for x in np.nditer(a,flags=['external_loop'], op_flags=['readwrite'],order='F'): # # nditer类的构造器有flags参数
    print(2*x,end=',') # 其中参数external_loop表示给出的值是具有多个值的一维数组,而不是零维数组
print('\n')
# 广播迭代
b = np.array([1,2,3,4],dtype = int)
for x,y in np.nditer([a,b]): # 如果两个数组是可广播的,nditer 组合对象能够同时迭代它们。
    print("%d:%d" % (x,y),end = ',') # a:3*4 b:1*4 (数组 b 被广播到 a 的大小)
print('\n')
[[0 1 2]
 [3 4 5]]
0,1,2,3,4,5,

0,3,1,4,2,5,

0,1,2,3,4,5,

0,3,1,4,2,5,

[[ 0  5 10 15]
 [20 25 30 35]
 [40 45 50 55]]
[[  0  10  20  30]
 [ 40  50  60  70]
 [ 80  90 100 110]]
[  0  80 160],[ 20 100 180],[ 40 120 200],[ 60 140 220],

0:1,10:2,20:3,30:4,40:1,50:2,60:3,70:4,80:1,90:2,100:3,110:4,

11. NumPy数组操作

Part 1

## NumPy数组操作
# 修改数组形状
# numpy.reshape 修改数组形状
a = np.arange(0,100,10)
np.reshape(a,(2,5),order='F') # 在不改变数据的条件下修改形状
print(a)
# numpy.ndarray.flat 数组元素迭代器
a = np.arange(9).reshape(3,3)
for element in a.flat: # 数组的flat属性(数组元素迭代器)
    print(element)
# numpy.ndarray.flatten 多维数组转为一维数组,返回一份数组拷贝
b = np.arange(8).reshape(2,4)
print(b) # 默认按照行优先
print(b.flatten()) # 展开的数组
print(b.flatten(order='F')) # 按照Fortran风格
# numpy.ravel 多维数组转为一维数组,没有必要不会产生副本,返回的是数组的视图(view),特别注意和flatten()区分
print(b.ravel())
print(b.ravel(order='F'))
# 翻转数组
# numpy.transpose 矩阵转置
x = np.arange(15).reshape(3,5)
print(x)
print(np.transpose(x)) # x.T
# numpy.rollaxis 向后滚动特定的轴到一个特定位置
# numpy.rollaxis(arr, axis, start) axis:要向后滚动的轴 start:默认0。会滚动到的特定位置。
a = np.arange(8).reshape(2,2,2)
print(a)
print(np.rollaxis(a,2)) # 把轴2滚动到轴0
print(np.rollaxis(a,2,1)) # 把轴2滚动到轴1,等价于交换轴1和轴2
# numpy.swapaxes 交换数组的两个轴
print(np.swapaxes(a,1,2)) # 交换轴1和轴2
[ 0 10 20 30 40 50 60 70 80 90]
0
1
2
3
4
5
6
7
8
[[0 1 2 3]
 [4 5 6 7]]
[0 1 2 3 4 5 6 7]
[0 4 1 5 2 6 3 7]
[0 1 2 3 4 5 6 7]
[0 4 1 5 2 6 3 7]
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
[[ 0  5 10]
 [ 1  6 11]
 [ 2  7 12]
 [ 3  8 13]
 [ 4  9 14]]
[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]
[[[0 2]
  [4 6]]

 [[1 3]
  [5 7]]]
[[[0 2]
  [1 3]]

 [[4 6]
  [5 7]]]
[[[0 2]
  [1 3]]

 [[4 6]
  [5 7]]]

 Part 2

# 修改数组维度
# numpy.broadcast 模仿广播的对象,并返回一个对象
x = np.array([[1],[2],[3]])
y = np.array([4,5,6])
b = np.broadcast(x,y) # b拥有iterator属性, 对y广播x
r,c = b.iters
print(next(r),next(c),next(r)) # 1 4 1 5 1 6 2 4 ...
print(b.shape)

b = np.broadcast(x,y) # 手动使用broadcast把x和y相加
c = np.empty(b.shape)
print(c.shape)
c.flat = [u + v for(u,v) in b]
print(c)
print(x + y)
# numpy.broadcast_to 将数组广播到新形状
a = np.arange(4).reshape(1,4)
print(a)
print(np.broadcast_to(a,(4,4))) # 把1*4广播到4*4的形状上
# numpy.expand_dims 在指定位置插入新的轴来扩展数组形状
# numpy.expand_dims(arr, axis)
x = np.array([[1,2],[3,4]])
y = np.expand_dims(x,axis = 0)
print(y)
print(x.shape, x.ndim, y.shape, y.ndim)
z = np.expand_dims(x,axis = 1)
print(z)
print(x.shape, x.ndim, z.shape, z.ndim)
# numpy.squeeze 从给定数组的形状中删除一维的条目
# numpy.squeeze(arr, axis)
a = np.arange(9).reshape(1,3,3)
print(a)
b = np.squeeze(a)
print(b)
print(a.shape, a.ndim, b.shape, b.ndim)
1 4 1
(3, 3)
(3, 3)
[[5. 6. 7.]
 [6. 7. 8.]
 [7. 8. 9.]]
[[5 6 7]
 [6 7 8]
 [7 8 9]]
[[0 1 2 3]]
[[0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]]
[[[1 2]
  [3 4]]]
(2, 2) 2 (1, 2, 2) 3
[[[1 2]]

 [[3 4]]]
(2, 2) 2 (2, 1, 2) 3
[[[0 1 2]
  [3 4 5]
  [6 7 8]]]
[[0 1 2]
 [3 4 5]
 [6 7 8]]
(1, 3, 3) 3 (3, 3) 2

Part 3

# 连接数组
# numpy.concatenate 用于沿指定轴连接相同形状的两个或多个数组
# numpy.concatenate((a1, a2, ...), axis)
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]]) # 两个数组的维度一致
print(np.concatenate((a,b))) # 默认axis = 0
print(np.concatenate((a,b), axis = 1)) # 沿着轴1连接两个数组
# numpy.stack 用于沿新轴连接数组序列
# numpy.stack(arrays, axis)
print (np.stack((a,b),0)) #沿轴0堆叠两个数组
print (np.stack((a,b),1)) #沿轴1堆叠两个数组
# numpy.hstack  numpy.stack 函数的变体,它通过水平堆叠来生成数组
c = np.hstack((a,b))
print(c)
# numpy.vstack numpy.stack 函数的变体,它通过垂直堆叠来生成数组
c = np.vstack((a,b))
print(c)
# 分割数组 
# numpy.split 沿特定的轴将数组分割为子数组
# numpy.split(ary, indices_or_sections, axis)
# indices_or_sections:如果是一个整数,就用该数平均切分,如果是一个数组,为沿轴切分的位置(左开右闭)
a = np.arange(9)
print(np.split(a,3))
print(np.split(a,[4,7]))
a = np.reshape(a,(3,3))
print(np.split(a,3))
# numpy.hsplit 用于水平分割数组,通过指定要返回的相同形状的数组数量来拆分原数组
b = np.floor(10 * np.random.random((2,6)))
print(b)
print(np.hsplit(b,3))
# numpy.vsplit
print(np.vsplit(b,2))
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
[[1 2 5 6]
 [3 4 7 8]]
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]
[[[1 2]
  [5 6]]

 [[3 4]
  [7 8]]]
[[1 2 5 6]
 [3 4 7 8]]
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
[array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8])]
[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]
[[9. 3. 2. 1. 4. 0.]
 [0. 7. 8. 9. 2. 6.]]
[array([[9., 3.],
       [0., 7.]]), array([[2., 1.],
       [8., 9.]]), array([[4., 0.],
       [2., 6.]])]
[array([[9., 3., 2., 1., 4., 0.]]), array([[0., 7., 8., 9., 2., 6.]])]

Part 4

# 数组元素的添加与删除
# numpy.resize 返回指定大小的新数组
# numpy.resize(arr, shape)
a = np.array([[1,2,3],[4,5,6]])
print(a)
b = np.resize(a,(3,2))
print(b)
c = np.resize(a,(4,2))
print(c) # 注意大小不一致,按照原数组元素顺序出现
# numpy.append 在数组的末尾添加值
# numpy.append(arr, values, axis=None)
print(np.append(a,[7,8,9]))  # 如果未提供轴,则输入数组会被展开。
print(np.append(a,[[7,8,9]],axis=0)) # 当axis无定义时,返回总是为一维数组
print(np.append(a,[[0,0,0],[7,8,9]],axis=1)) # 沿轴 1 添加元素
# numpy.insert 在给定索引之前,沿给定轴在输入数组中插入值
# numpy.insert(arr, obj, values, axis)
x = np.array([[1,2],[3,4],[5,6]])
print(x)
print(np.insert(x,3,[11,12])) # 未传递axis参数 在插入之前输入数组会被展开
print(np.insert(x,1,[11,12],axis = 0)) # 广播形式匹配输入数组
print(np.insert(x,1,0,axis = 1)) # 同上
# numpy.delete 返回从输入数组中删除指定子数组的新数组
# numpy.delete(arr, obj, axis)
y = np.arange(12).reshape(3,4)
print(y)
print(np.delete(y,5)) # 与insert()函数的情况一样,如果未提供axis参数,则输入数组将展开
print(np.delete(y,1,axis=1)) # 删除第2列的元素
z = np.arange(10)
print(np.delete(z,np.s_[::2])) # 从数组中根据切片删除子数组
# numpy.unique 去除数组中的重复元素
# numpy.unique(arr, return_index, return_inverse, return_counts)
# arr:输入数组,如果不是一维数组则会展开
a = np.array([5,2,6,2,7,5,6,8,2,9])
print(a)
u = np.unique(a)
print(u)
u,indices = np.unique(a, return_index = True)
print(indices) # return_index:如果为true,返回新列表元素在旧列表中的位置(下标),并以列表形式储
u,indices = np.unique(a, return_inverse = True)
print(indices) # return_inverse:如果为true,返回旧列表元素在新列表中的位置(下标),并以列表形式储
print(u[indices]) # 使用下标重构原数组
u,indices = np.unique(a,return_counts = True)
print(u)
print(indices) # return_counts:如果为true,返回去重数组中的元素在原数组中的出现次数
[[1 2 3]
 [4 5 6]]
[[1 2]
 [3 4]
 [5 6]]
[[1 2]
 [3 4]
 [5 6]
 [1 2]]
[1 2 3 4 5 6 7 8 9]
[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[1 2 3 0 0 0]
 [4 5 6 7 8 9]]
[[1 2]
 [3 4]
 [5 6]]
[ 1  2  3 11 12  4  5  6]
[[ 1  2]
 [11 12]
 [ 3  4]
 [ 5  6]]
[[1 0 2]
 [3 0 4]
 [5 0 6]]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[ 0  1  2  3  4  6  7  8  9 10 11]
[[ 0  2  3]
 [ 4  6  7]
 [ 8 10 11]]
[1 3 5 7 9]
[5 2 6 2 7 5 6 8 2 9]
[2 5 6 7 8 9]
[1 0 2 4 7 9]
[1 0 2 0 3 1 2 4 0 5]
[5 2 6 2 7 5 6 8 2 9]
[2 5 6 7 8 9]
[3 2 2 1 1 1]

12. NumPy位运算

## NumPy 位运算
a,b = 13,17
print(bin(a),bin(b))
print(np.bitwise_and(a,b)) # bitwise_and() 函数对数组中整数的二进制形式执行位与运算。
print(np.bitwise_or(a,b)) # bitwise_or()函数对数组中整数的二进制形式执行位或运算。
# invert 对数组中整数进行位取反运算
print(np.invert(np.array([13],dtype = np.uint8))) # 无符号整数
print (np.binary_repr(13, width = 8)) # 宽度为8,下同
print (np.binary_repr(242, width = 8)) # 注意实现了位的取反
# left_shift
# left_shift() 函数将数组元素的二进制形式向左移动到指定位置,右侧附加相等数量的 0。
print(np.left_shift(10,2)) # 10==>40
print(np.binary_repr(10,width=8))
print(np.binary_repr(40,width=8))
# right_shift
# right_shift() 函数将数组元素的二进制形式向右移动到指定位置,左侧附加相等数量的 0。
print(np.right_shift(40,2)) # 40==>10
0b1101 0b10001
1
29
[242]
00001101
11110010
40
00001010
00101000
10

13. NumPy字符串函数

## NumPy 字符串函数
print(np.char.add(['scu'],['cs'])) # 依次对两个数组的元素进行字符串连接
print(np.char.add(['scu','hello'],['cs','world'])) 
print(np.char.multiply('PY',3)) # 执行多重连接
print(np.char.center('python',20,fillchar='*')) # 将字符串居中,并使用指定字符在左侧和右侧进行填充
print(np.char.capitalize('python')) # 将字符串的第一个字母转换成大写
print(np.char.title('i love python'))# 将字符串的每个单词的第一个字母转换为大写
print(np.char.lower(['SCU','CS'])) # 对数组的每个元素转换为小写
print(np.char.upper(['computer','science'])) #对数组的每个元素转换为大写
print(np.char.split('I love Python!')) # 通过指定分隔符对字符串进行分割,并返回数组。默认情况下,分隔符为空格
print(np.char.split('www.google.com.hk',sep = '.'))
print(np.char.splitlines('i\nlike python!')) # 以换行符作为分隔符来分割字符串,并返回数组。\n,\r,\r\n 都可用作换行符。
print(np.char.strip('super star','s'))
print(np.char.strip(['apple','alibaba','amazon','facebook'],'a')) # 用于移除开头或结尾处的特定字符
print(np.char.join(':','computer'))
print(np.char.join(['-',':'],['SCU','CS'])) # 通过指定分隔符来连接数组中的元素或字符串
print(np.char.replace('i like abble','bb','pp')) # 使用新字符串替换字符串中的所有子字符串
a = np.char.encode('scucs','cp500')
print(a)# 对数组中的每个元素调用 str.encode 函数,默认编码是 utf-8
b = np.char.decode(a,'cp500')
print(b)
['scucs']
['scucs' 'helloworld']
PYPYPY
*******python*******
Python
I Love Python
['scu' 'cs']
['COMPUTER' 'SCIENCE']
['I', 'love', 'Python!']
['www', 'google', 'com', 'hk']
['i', 'like python!']
uper star
['pple' 'libab' 'mazon' 'facebook']
c:o:m:p:u:t:e:r
['S-C-U' 'C:S']
i like apple
b'\xa2\x83\xa4\x83\xa2'
scucs

14. NumPy数学函数

## NumPy数学函数
x = np.array([0,30,45,60,90])
y = np.sin(x*np.pi/180)
print(y)
z = np.arcsin(y)
print(np.degrees(z)) # 将弧度转换为角度
a = np.array([1.0,3.55,4.6,9.01,23.888])
print(np.around(a))
print(np.around(a,decimals = 1)) # 函数返回指定数字的四舍五入值
print(np.around(a,decimals = -1))
b = np.array([-1.4,1.5,-0.2,0.6,10])
print(np.floor(b)) # 向下取整
print(np.ceil(b)) # 向上取整
[0.         0.5        0.70710678 0.8660254  1.        ]
[ 0. 30. 45. 60. 90.]
[ 1.  4.  5.  9. 24.]
[ 1.   3.6  4.6  9.  23.9]
[ 0.  0.  0. 10. 20.]
[-2.  1. -1.  0. 10.]
[-1.  2. -0.  1. 10.]

15. NumPy算术函数

## NumPy算术函数
a = np.arange(9,dtype = np.float_).reshape(3,3)
b = np.array([10,10,10])
print(a,b)
print(np.add(a,b)) # 数组相加
print(np.subtract(a,b)) # 数组相减
print(np.multiply(a,b)) # 数组相乘
print(np.divide(a,b)) # 数组相除
c = np.array([0.25,0.5,20,100])
print(c)
print(np.reciprocal(c)) # 返回参数逐元素的倒数
x = np.array([1,2,3])
y = np.array([10,100,1000])
print(np.power(x,2)) # 将第一个输入数组中的元素作为底数,计算它与第二个输入数组中相应元素的幂
print(np.power(y,x))
a = np.array([10,20,30])
b = np.array([3,5,7])
print(np.mod(a,b))
print(np.remainder(a,b)) # 计算输入数组中相应元素的相除后的余数
[[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]] [10 10 10]
[[10. 11. 12.]
 [13. 14. 15.]
 [16. 17. 18.]]
[[-10.  -9.  -8.]
 [ -7.  -6.  -5.]
 [ -4.  -3.  -2.]]
[[ 0. 10. 20.]
 [30. 40. 50.]
 [60. 70. 80.]]
[[0.  0.1 0.2]
 [0.3 0.4 0.5]
 [0.6 0.7 0.8]]
[  0.25   0.5   20.   100.  ]
[4.   2.   0.05 0.01]
[1 4 9]
[        10      10000 1000000000]
[1 0 2]
[1 0 2]

 16. NumPy统计函数

## NumPy 统计函数
a = np.array([[3,7,5],[8,4,3],[2,4,9]])  
print(a)
print(np.amin(a, axis = 1)) # 计算数组中的元素沿指定轴的最小值
print(np.amax(a, 0)) # 计算数组中的元素沿指定轴的最大值
print(np.amax(a)) # 计算数组中的元素的最大值
print(np.ptp(a)) # 计算数组中元素最大值与最小值的差
print(np.ptp(a, axis = 1)) # 沿着轴1调用
print(np.ptp(a, axis = 0)) # 沿着轴0调用
# numpy.percentile(a, q, axis) 百分位数是统计中使用的度量,表示小于这个值的观察值的百分比
x = np.array([[10,7,4],[3,2,1]])
print(x)
print(np.percentile(x, 50)) # 计算数组的百分位数
print(np.percentile(x,50, axis = 0)) # 沿着纵列计算
print(np.percentile(x,50, axis = 1)) # 沿着横行计算(2*1)
print(np.percentile(x,50, axis = 1, keepdims = True)) # 保持维度不变(1*2)
x = np.append(x,[[6,4,9]],axis = 0)
print(x) 
print(np.median(x)) # 计算数组中元素的中位数(中值)
print(np.median(x, axis = 0)) # 沿着纵列计算
print(np.median(x, axis = 1)) # 沿着横行计算
print(np.mean(x)) # 计算数组中元素的算术平均值
print(np.mean(x, axis = 0)) # 沿着纵列计算
print(np.mean(x, axis = 1)) # 沿着横行计算
a = np.array([1,2,3,4])
print(np.average(a)) # 计算数组中元素的平均值。没有指定权重时相当于mean()
w = np.array([4,3,2,1]) # 权重
print(np.average(a,weights = w)) # 加权平均值
a = a.reshape(1,4)
a = np.insert(a,1,[[5,6,7,8]],axis = 0)
print(a)
print(np.average(a,axis = 0)) # 沿着纵列计算
print(np.average(a,axis = 1)) # 沿着横行计算
x = np.arange(5)
print(np.std(x)) # 计算标准差 std = sqrt(mean((x - x.mean())**2))
print(np.var(x)) # 计算方差 标准差就是方差的算术平方根
[[3 7 5]
 [8 4 3]
 [2 4 9]]
[3 3 2]
[8 7 9]
9
7
[4 5 7]
[6 3 6]
[[10  7  4]
 [ 3  2  1]]
3.5
[6.5 4.5 2.5]
[7. 2.]
[[7.]
 [2.]]
[[10  7  4]
 [ 3  2  1]
 [ 6  4  9]]
4.0
[6. 4. 4.]
[7. 2. 6.]
5.111111111111111
[6.33333333 4.33333333 4.66666667]
[7.         2.         6.33333333]
2.5
2.0
[[1 2 3 4]
 [5 6 7 8]]
[3. 4. 5. 6.]
[2.5 6.5]
1.4142135623730951
2.0

 17. NumPy排序、条件刷选函数

## NumPy 排序、条件刷选函数
# numpy.sort() 函数返回输入数组的排序副本
# numpy.sort(a, axis, kind, order)
a = np.array([[3,7,2],[9,1,5]])
print(a)
print(np.sort(a)) # 按照横行排序
print(np.sort(a, axis = 0)) # 按照纵列排序
dt = np.dtype([('name','S10'),('age',int)]) # 定义数据结构
a = np.array([('tom',20),('jerry',25),('alice',18),('bob',30)],dtype = dt)
print(a)
print(np.sort(a,kind = 'heapsort', order = 'name'))  # kind默认是'quciksort'
print(np.sort(a,kind = 'mergesort',order = 'age'))
# numpy.argsort() 返回的是数组值从小到大的索引值
b = np.argsort(a)
print(b) # 排序后在原数组中的索引值
print(a[b]) # 重构原数组
for i in b:
    print(a[i], end="**") # 使用迭代器循环重构
print('\n')
# numpy.lexsort() 对多个序列进行排序
nm =  ('raju','anil','ravi','amar') 
dv =  ('f.y.',  's.y.',  's.y.',  'f.y.') 
ind = np.lexsort((dv,nm)) # 每一列代表一个序列,排序时优先照顾靠后的列
print(ind) # 获得新数组元素在原数组中的索引
print([nm[i]+','+dv[i] for i in ind])
# numpy,sort_complex() 对复数按照先实部后虚部的顺序进行排序。
a = np.array([1+2j, 1-2j, 2+3j, 3, 4-1j],dtype = 'complex')
print(np.sort_complex(a))
# partition(a, kth[, axis, kind, order]) 指定一个数,对数组进行分区
x = np.array([3,4,2,1])
print(np.partition(x,3)) # 将数组 a 从小到大排列,比第3小的放在前面,大的放在后面
print(np.partition(x,(1,3))) # 小于1的在前面,大于3 的在后面,1和3之间的在中间
# argpartition(a, kth[, axis, kind, order]) 可以通过关键字 kind 指定算法沿着指定轴对数组进行分区
a = np.array([46, 57, 23, 39, 1, 10, 0, 120])
print(a[np.argpartition(a,2)[2]]) # 找到数组的第 3 小(index=2)的值
print(a[np.argpartition(a,-2)[-2]]) # 找到数组的第 2 大(index=-2)的值
idx = np.argpartition(a,[2,3]) # 用 [2,3] 同时将第 3 和第 4 小的排序好
print(a[idx[2:4:1]])
# numpy.argmax() 和 numpy.argmin() 分别沿给定轴返回最大和最小元素的索引
a = np.array([[3,4,7],[8,2,1],[5,9,6]])  
print(a)
print(np.argmax(a)) # 展开数组后最大元素的索引
print(np.argmax(a, axis = 0)) # 沿着纵列最大元素的索引
print(np.argmax(a, axis = 1)) # 沿着横行最大元素的索引
print(np.argmin(a, axis = 0)) # 沿着纵列最小元素的索引
print(np.argmin(a, axis = 1)) # 沿着横行最小元素的索引
# numpy.nonzero() 返回输入数组中非零元素的索引
a = np.array([[20,0,-1],[0,10,-5],[0,0,90]])
print(a)
print(np.nonzero(a)) # 分别返回各位维度的索引数组
# numpy.where() 返回输入数组中满足给定条件的元素的索引
idx = np.where(a>0) # 大于0的元素的索引
print(a[idx]) # 重构大于0的元素的数组
# numpy.extract() 根据某个条件从数组中抽取元素,返回满足条件的元素
condition = np.mod(a,2)==1 # 定义条件(选择奇数元素)
print(np.extract(condition,a)) # 使用条件提取出奇数元素
[[3 7 2]
 [9 1 5]]
[[2 3 7]
 [1 5 9]]
[[3 1 2]
 [9 7 5]]
[(b'tom', 20) (b'jerry', 25) (b'alice', 18) (b'bob', 30)]
[(b'alice', 18) (b'bob', 30) (b'jerry', 25) (b'tom', 20)]
[(b'alice', 18) (b'tom', 20) (b'jerry', 25) (b'bob', 30)]
[2 3 1 0]
[(b'alice', 18) (b'bob', 30) (b'jerry', 25) (b'tom', 20)]
(b'alice', 18)**(b'bob', 30)**(b'jerry', 25)**(b'tom', 20)**

[3 1 0 2]
['amar,f.y.', 'anil,s.y.', 'raju,f.y.', 'ravi,s.y.']
[1.-2.j 1.+2.j 2.+3.j 3.+0.j 4.-1.j]
[2 1 3 4]
[1 2 3 4]
10
57
[10 23]
[[3 4 7]
 [8 2 1]
 [5 9 6]]
7
[1 2 0]
[2 0 1]
[0 1 1]
[0 2 0]
[[20  0 -1]
 [ 0 10 -5]
 [ 0  0 90]]
(array([0, 0, 1, 1, 2], dtype=int64), array([0, 2, 1, 2, 2], dtype=int64))
[20 10 90]
[-1 -5]

18. NumPy字节交换

大端模式:指数据的高字节保存在内存的低地址中,而数据的低字节保存在内存的高地址中,这样的存储模式有点儿类似于把数据当作字符串顺序处理:地址由小向大增加,而数据从高位往低位放;这和我们的阅读习惯一致。

小端模式:指数据的高字节保存在内存的高地址中,而数据的低字节保存在内存的低地址中,这种存储模式将地址的高低和数据位权有效地结合起来,高地址部分权值高,低地址部分权值低。

## NumPy字节交换
a = np.array([1,2,3], dtype = np.int8)
print(a)
print(map(hex,a)) # 以十六进制表示内存中的数据
print (a.byteswap(True)) # 传入True来原地交换
print(map(hex,a))
[1 2 3]
<map object at 0x000001C0272D69C8>
[1 2 3]
<map object at 0x000001C0272D6908>

 19. NumPy副本和视图

副本:数据的完整拷贝。对副本进行修改不会影响原始数据,它们的物理内存不在同一位置。可以调用ndarray的copy()产生副本。

视图:数据的别称或引用,可以通过这个别称或引用访问、操作原始数据,它们的物理内存在同一位置。可以调用ndarray的view()产生视图。NumPy的切片操作返回原数组的视图。

## NumPy 副本和视图
# 无复制
# 简单的赋值不会创建数组对象的副本。
# 相反它使用原始数组的相同id()来访问它。id()返回 Python 对象的通用标识符,类似于 C 中的指针。
a = np.arange(8)
print(a)
print(id(a)) # 对象a的通用标识符
b = a
print(b) # 直接赋值给b
print(id(b))
b.shape = 2,4
print(b)
print(a) # 一个数组的形状改变也会改变另一个数组的形状
# 视图或浅拷贝
# ndarray.view() 会创建一个新的数组对象
x = np.arange(6).reshape(3,2)
print(x)
y = x.view()
print(y)
print(id(x),id(y)) # 两个数组的id()是不同的
y.shape = 2,3
print(y)
print(x) # 两个数组的形状也是不同的
a = np.arange(12)
print(a)
a1 = a[3:] # 使用切片创建视图会影响到原始数组
a2 = a[3:]
a1[1]=99
print(a) # 没有变化
print(id(a1),id(a2)) # a1和a2是a的视图,但是它们的id()仍然是不同的,和直接赋值引用不同
# 副本或深拷贝 创建一个副本(在物理内存上不在同一位置)
a = np.arange(6).reshape(3,2)
print(a)
b = a.copy() # 深层副本
print(b is a)
b[0,0] = 999
print(a)
print(b) # 对副本进行修改,不影响原始数组
[0 1 2 3 4 5 6 7]
1924802866752
[0 1 2 3 4 5 6 7]
1924802866752
[[0 1 2 3]
 [4 5 6 7]]
[[0 1 2 3]
 [4 5 6 7]]
[[0 1]
 [2 3]
 [4 5]]
[[0 1]
 [2 3]
 [4 5]]
1924802883632 1924802606704
[[0 1 2]
 [3 4 5]]
[[0 1]
 [2 3]
 [4 5]]
[ 0  1  2  3  4  5  6  7  8  9 10 11]
[ 0  1  2  3 99  5  6  7  8  9 10 11]
1924802843712 1924802844592
[[0 1]
 [2 3]
 [4 5]]
False
[[0 1]
 [2 3]
 [4 5]]
[[999   1]
 [  2   3]
 [  4   5]]

 20. NumPy矩阵库

NumPy 中包含了一个矩阵库 numpy.matlib,该模块中的函数返回的是一个矩阵(matrix)。

## NumPy矩阵库  numpy.matlib
# numpy.matlib.empty(shape, dtype, order) 返回一个新的矩阵
print (np.matlib.empty((2,2),dtype = np.float_,order = 'C'))
# numpy.matlib.zeros() 创建一个以 0 填充的矩阵
print (np.matlib.zeros((3,3)))
# numpy.matlib.ones() 创建一个以 1 填充的矩阵
print (np.matlib.ones((2,2),dtype = np.int8))
# numpy.matlib.eye(n, M,k, dtype) 返回一个矩阵,对角线元素为 1,其他位置为零
print (np.matlib.eye(n = 3, M = 4, k =0, dtype =  float)) # n:矩阵的行数 M: 矩阵的列数,默认为 n k:对角线的索引
# numpy.matlib.identity() 返回给定大小的单位矩阵
print (np.matlib.identity(4,dtype = float))
# numpy.matlib.rand() 创建一个给定大小的矩阵,数据是随机填充的
print (np.matlib.rand(3,3)) 
m = np.matrix('1,2;3,4')
print(m)
n = np.asarray(m) # 把矩阵转换成ndarray的二维数组
print(n)
k = np.asmatrix(n) # 把二维数字转换成矩阵
print(k)
[[1. 1.]
 [1. 1.]]
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
[[1 1]
 [1 1]]
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]]
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]
[[0.72636853 0.09921164 0.96760239]
 [0.88451049 0.83393199 0.02119278]
 [0.7677641  0.78156854 0.74535761]]
[[1 2]
 [3 4]]
[[1 2]
 [3 4]]
[[1 2]
 [3 4]]

21. NumPy线性代数

NumPy 提供了线性代数函数库linalg,该库包含了线性代数所需的所有功能。

## NumPy线性代数
# numpy.dot(a, b, out=None)   两个一维数组:点积 二维数组:矩阵乘法 
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
print(np.dot(a,b)) # 矩阵乘法
print(np.dot(a[0],b[0])) # 数组点积
# numpy.vdot() 两个向量的点积
print(np.vdot(a,b)) # 对于多维数组,将数组展开成向量
# numpy.inner() 一维数组:向量内积 更高维度:两个数组的行与行乘积和运算
print(np.inner(np.array([1,2,3]),np.array([0,1,1])))
print(np.inner(a,b))
# numpy.matmul() 两个数组的矩阵乘积
a = np.array([[1,0],[0,1]])
b = np.array([[4,1],[2,2]])
print(np.matmul(a,b)) # 二维数组:矩阵乘法
c = [1,2] # 二维数组和一维数组
print(np.matmul(a,c)) # 如果任一参数是一维数组,则在其维度上附加将其转换为矩阵
print(np.matmul(c,a)) # 并在乘法之后被去除
# 如果任一参数的维数大于2,该参数被理解为一些矩阵(参数的最后两个维数为矩阵维数)的stack,而且计算时会相应的广播
x = np.arange(8).reshape(2,2,2)
y = np.arange(4).reshape(2,2)
print(np.matmul(x,y))
# numpy.linalg.det() 计算输入矩阵的行列式
print(np.linalg.det(b))
# numpy.linalg.solve() 给出了矩阵形式的线性方程的解
# numpy.linalg.inv() 计算矩阵的乘法逆矩阵
a = np.array([[1,2],[3,4]])
print(a)
b = np.linalg.inv(a)
print(b)
print(np.dot(a,b))
X = np.array([[1,1,1],[0,2,5],[2,5,-1]]) 
Y = np.array([[6],[-4],[27]]) 
print(np.linalg.solve(X,Y)) # 计算线性方程组
[[19 22]
 [43 50]]
17
70
5
[[17 23]
 [39 53]]
[[4 1]
 [2 2]]
[1 2]
[1 2]
[[[ 2  3]
  [ 6 11]]

 [[10 19]
  [14 27]]]
6.0
[[1 2]
 [3 4]]
[[-2.   1. ]
 [ 1.5 -0.5]]
[[1.00000000e+00 1.11022302e-16]
 [0.00000000e+00 1.00000000e+00]]
[[ 5.]
 [ 3.]
 [-2.]]

22. NumPy IO

## NumPy IO
# NumPy 为 ndarray 对象引入了一个简单的文件格式:npy。
# npy 文件用于存储重建 ndarray 所需的数据、图形、dtype 和其他信息。
# numpy.save(file, arr, allow_pickle=True, fix_imports=True) 将数组保存到以 .npy 为扩展名的文件
a = np.array([1,2,3,4,5])
name = 'outfile.npy'
# np.save(name,a)
x = np.load(name)
print(x)
# numpy.savez(file, *args, **kwds) 将多个数组保存到以 npz 为扩展名的文件中
b = np.arange(0,1.0,0.1)
c = np.sin(b)
np.savez('files.npz',a,b,sin = c)
r = np.load('files.npz')
print(r.files) # 查看数组名称
print(r['sin']) 
print(r['arr_0']) 
print(r['arr_1']) # 查看各数组
# savetxt() 以简单的文本文件格式存储数据,对应的使用 loadtxt() 函数来获取数据。
# np.loadtxt(FILENAME, dtype=int, delimiter=' ')
# np.savetxt(FILENAME, a, fmt="%d", delimiter=",")
np.savetxt('out.txt',a)
b = np.loadtxt('out.txt')
print(b)
a=np.arange(0,10,0.5).reshape(4,-1)
np.savetxt("out.txt",a,fmt="%f",delimiter=",") # 保存为小数,以逗号分隔
b = np.loadtxt("out.txt",dtype = float, delimiter=",") # 也要指定为逗号分隔
print(b)
[1 2 3 4 5]
['sin', 'arr_0', 'arr_1']
[0.         0.09983342 0.19866933 0.29552021 0.38941834 0.47942554
 0.56464247 0.64421769 0.71735609 0.78332691]
[1 2 3 4 5]
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
[1. 2. 3. 4. 5.]
[[0.  0.5 1.  1.5 2. ]
 [2.5 3.  3.5 4.  4.5]
 [5.  5.5 6.  6.5 7. ]
 [7.5 8.  8.5 9.  9.5]]

23. NumPy Matplotlib

Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。

## NumPy Matplotlib
from matplotlib import pyplot as plt 
import matplotlib
x = np.arange(-5,5,0.5)
y = 2 * x - 2
plt.title("demo")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.plot(x,y)
plt.show()
# 添加格式字符串 
x = np.arange(0,3*np.pi,0.1)
y = np.sin(x)
plt.title("sine wave form")
plt.plot(x,y,'or')  # o:圆标记 r:red
plt.show()
# subplot() 函数允许你在同一图中绘制不同的东西。
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.subplot(2,1,1)
plt.plot(x,y_sin)
plt.title('Sine')
plt.subplot(2,1,2)
plt.plot(x,y_cos)
plt.title('Cosine')
plt.show()

# pyplot子模块提供 bar() 函数来生成条形图
from matplotlib import pyplot as plt 
x =  [5,8,10] 
y =  [12,16,6] 
x2 =  [6,9,11] 
y2 =  [6,15,7] 
plt.bar(x, y, align =  'center') 
plt.bar(x2, y2, color =  'g', align =  'center') 
plt.title('Bar graph') 
plt.ylabel('Y axis') 
plt.xlabel('X axis') 
plt.show()
# numpy.histogram() 函数是数据的频率分布的图形表示
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
np.histogram(a,bins =  [0,20,40,60,80,100]) 
hist,bins = np.histogram(a,bins =  [0,20,40,60,80,100])  
print (hist) 
print (bins)
# pyplot子模块的 plt() 函数将包含数据和 bin 数组的数组作为参数,并转换为直方图
plt.hist(a,bins =  [0,20,40,60,80,100])
plt.title("histogram") 
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值