NumPy基础
●NumPy ( Numerical Python , NumPy )库长期以来一直是Python科学计算的基石,它提供了数值数据的大多数科学应用所需的数据结构和算
法,还有包括以下:
●快速高效的多维数组的对象(numpy.ndarray)
●用于对数组执行元素级计算以及直接对数组执行数学运算的函数
●用于读写硬盘上基于数组的数据集的工具
●线性代数运算、傅里叶变换以及随机数生成
●用于集成由C、C++、Fortran等语言编写的代码的工具
●许多数值计算要么直接使用NumPy的数组作为其主要数据类型,要么兼容NumPy的数据类型
●NumPy数组在存储和处理数值数据时要比内置的Python数据结构高效得多
●NumPy在数据分析中的重要用途之- 是作为算法和工具库之间的传递容器
NumPy核心数据类型
●NumPy提供了一个N维数组类型ndarray ( numpy.ndarray) , 它描述了相同类型的元素的集合
●ndarray与原生Python列表的区别:
●ndarray数据与数据的地址都是连续的,而Python列表存储的是引用地址
●ndarray中的所有元素的类型都是相同的,而Python列表中的元素类型是任意的
●ndarray内置了并行运算功能,当系统有多个核心时, NumPy会自动做并行计算
numpy函数简单应用
import numpy as np
a = np.arange(10)
print(a)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(a.dtype)
dtype('int64')
print(a.shape)
(10,)
# 用linspace函数创建一个初始值为1 ,终止值为19 ,元素个数为10个的等差数列向量
b = np.linspace(1,19,10)
b
array([ 1., 3., 5., 7., 9., 11., 13., 15., 17., 19.])
# endpoint参数指定是否包含终止值
np.linspace(1,19,10,endpoint=False)
array([ 1. , 2.8, 4.6, 6.4, 8.2, 10. , 11.8, 13.6, 15.4, 17.2])
# 用logspace函数创建一个等比数列向量,基数可以通过base参数指定,默认值为10
from math import e# 引入自然数e
np.logspace(1,20,10,endpoint=False,base=e)
array([2.71828183e+00, 1.81741454e+01, 1.21510418e+02, 8.12405825e+02,
5.43165959e+03, 3.63155027e+04, 2.42801617e+05, 1.62334599e+06,
1.08535199e+07, 7.25654884e+07])
# 用zeros函数创建一个元素全部为0的整数型向量
np.zeros(10,np.int)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
# 创建一个随机数向量, randn是numpy.random中生成正态分布随机数据的函数
np.random.randn(10)
array([ 0.04384946, -1.97646467, 0.56858477, -0.1958997 , -1.43684069,
-1.09261095, 0.17620979, -0.93042159, -0.41511684, -1.22303696])
# shape属性表示数组的形状, ndim属性表示数组的维数。
c = np.array([np.arange(3),np.arange(3)])
print(c)
print(c.shape)
print(c.ndim)
[[0 1 2]
[0 1 2]]
(2, 3)
2
# 创建单位矩阵
np.identity(9).astype(np.int8)
array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=int8)
c.tolist()
[[0, 1, 2], [0, 1, 2]]
# 查看完整的ndarray数据类型
print(set(np.typeDict.values()))
{<class 'numpy.complex256'>, <class 'numpy.float128'>, <class 'numpy.uint64'>, <class 'numpy.int64'>, <class 'numpy.str_'>, <class 'numpy.complex128'>, <class 'numpy.float64'>, <class 'numpy.uint32'>, <class 'numpy.int32'>, <class 'numpy.bytes_'>, <class 'numpy.complex64'>, <class 'numpy.float32'>, <class 'numpy.uint16'>, <class 'numpy.int16'>, <class 'numpy.bool_'>, <class 'numpy.timedelta64'>, <class 'numpy.float16'>, <class 'numpy.uint8'>, <class 'numpy.int8'>, <class 'numpy.object_'>, <class 'numpy.datetime64'>, <class 'numpy.uint64'>, <class 'numpy.int64'>, <class 'numpy.void'>}
# 结构数组
# 个购物清单,包含的字段主要有:商品名称、购买地点、价格、数量,可以事先使用dtype函数自定义这些字段的类型:
goodslist = np.dtype([('name',np.str_,50),('location',np.str_,30),('price',np.float16),('number',np.int32)])
goodslist
dtype([('name', '<U50'), ('location', '<U30'), ('price', '<f2'), ('number', '<i4')])
goods = np.array([('Gree Airconditioner','JD.com',6245,1),('Sony Blueray Player','Amonzon.com',3210,2),('Apple Macbook Pro 13','Tmall.com',12388,5),('iPhoneSE','JD.com',4588,2)],dtype=goodslist)
goods
array([('Gree Airconditioner', 'JD.com', 6244., 1),
('Sony Blueray Player', 'Amonzon.com', 3210., 2),
('Apple Macbook Pro 13', 'Tmall.com', 12380., 5),
('iPhoneSE', 'JD.com', 4588., 2)],
dtype=[('name', '<U50'), ('location', '<U30'), ('price', '<f2'), ('number', '<i4')])
goodsdict = np.dtype({'names':['name','location','price','number'],'formats':['U50','U30','f','i']})
goods_new = np.array([('Gree Airconditioner','JD.com',6245,1),('Sony Blueray Player','Amonzon.com',3210,2),('Apple Macbook Pro 13','Tmall.com',12388,5),('iPhoneSE','JD.com',4588,2)],dtype=goodsdict)
goods_new
array([('Gree Airconditioner', 'JD.com', 6245., 1),
('Sony Blueray Player', 'Amonzon.com', 3210., 2),
('Apple Macbook Pro 13', 'Tmall.com', 12388., 5),
('iPhoneSE', 'JD.com', 4588., 2)],
dtype=[('name', '<U50'), ('location', '<U30'), ('price', '<f4'), ('number', '<i4')])
# 多维数组
# shape直接修改内存地址中数组的形状而reshape不会修改,即shape会修改原始数组, reshape不会修改。
d = np.arange(24).reshape(2,3,4)
d
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
d[1,1,2]
18
d[0,...]# d[0,;,;]
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
d[d>=15]
array([15, 16, 17, 18, 19, 20, 21, 22, 23])
# ndarray对象的latten方法与ravel函数功能相同,但执行flatten函数后,会分配内存保存结果; ravel函数只是返回数组的一个视图。
# 将为一维数组
print(d.ravel())
print(c.flatten())
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
[0 1 2 0 1 2]
# 转置函数a.T np.transpose(a)
# 水平组合即把所有参加组合的数组拼接起来,各数组行数应该相等.函数hstack和concatenate的效果相同,注意垂直组合时concatenate函数中参数axis=0
# 绝对值
m = np.array([1,-2,3,-6,-9,10])
np.abs(m)
array([ 1, 2, 3, 6, 9, 10])
# 平方
np.square(m)
array([ 1, 4, 9, 36, 81, 100])
# numpy中对数组的操作函数
# 平方根sqrt() 以e为底的指数exp() 以e为底的对数log(),以2为底的对数log2(),等等
# 返回各元素的符号sign() 对数组排序sort(),默认升序,对多维数组可在不同轴上排序,对横轴:参数axis=1
# 去除重复元素unique() 向上取整ceil() 向下取整floor() 四舍五入rint() 小数部分和整数部分分离modf()
# 三角函数sin() cos() tan() 求和sum() 求平均数mean() 求标准差std() 求方差var() 最小值min() 最大值max()
# 最小元素索引argmin() 最大元素索引argmax()
# 计算累计和cumsum()
np.cumsum(m)
array([ 1, -1, 2, -4, -13, -3])
# 计算累计积cumprod()
np.cumprod(m)
array([ 1, -2, -6, 36, -324, -3240])
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 矩阵操作
# 返回矩阵的对角线元素
np.diag(a)
array([1, 5, 9])
# 若为一维数组,则返回对角矩阵
m = np.array([1,3])
np.diag(m)
array([[1, 0],
[0, 3]])
# 计算对角线元素之和trace() 计算矩阵的行列式(线性代数知识:主对角线之和-次对角线之和)np.linalg.det()
# 矩阵的逆np.linalg.inv() 矩阵点乘np.dot(a,b)
# np.random库产生随机数
np.random.rand(2,3) # 产生0,1之间的服从均匀分布的随机数
array([[0.85317681, 0.4408503 , 0.41369915],
[0.02701161, 0.29895793, 0.14457146]])
np.random.randint(0,20,size=10) # 给定上下限和数据个数,产生随机整数
array([13, 17, 17, 0, 5, 3, 17, 5, 10, 19])
np.random.binomial(10,0.5)# 产生满足二项分布的随机数
7