Python 科学计算库numpy

Numpy基础数据结构

NumPy数组是一个多维数组对象,称为ndarray。其由两部分组成:

  • 实际的数据
  • 描述这些数据的元数

# 多维数组ndarray

import numpy as np

ar = np.array([1,2,3,4,5,6,7])
print(ar)          # 输出数组,注意数组的格式:中括号,元素之间没有逗号(和列表区分)
print(ar.ndim)     # 输出数组维度的个数(轴数),或者说“秩”,维度的数量也称rank
print(ar.shape)    # 数组的维度,对于n行m列的数组,shape为(n,m)
print(ar.size)     # 数组的元素总数,对于n行m列的数组,元素总数为n*m
print(ar.dtype)    # 数组中元素的类型,类似type()(注意了,type()是函数,.dtype是方法)
print(ar.itemsize) # 数组中每个元素的字节大小,int32l类型字节为4,float64的字节为8
print(ar.data)     # 包含实际数组元素的缓冲区,由于一般通过数组的索引获取元素,所以通常不需要使用这个属性。
ar   # 交互方式下输出,会有array(数组)

# 数组的基本属性
# ① 数组的维数称为秩(rank),一维数组的秩为1,二维数组的秩为2,以此类推
# ② 在NumPy中,每一个线性的数组称为是一个轴(axes),秩其实是描述轴的数量:
# 比如说,二维数组相当于是两个一维数组,其中第一个一维数组中每个元素又是一个一维数组
# 所以一维数组就是NumPy中的轴(axes),第一个轴相当于是底层数组,第二个轴是底层数组里的数组。
# 而轴的数量——秩,就是数组的维数。

# 创建数组:arange(),类似range(),在给定间隔内返回均匀间隔的值。

# 创建数组:linspace():返回在间隔[开始,停止]上计算的num个均匀间隔的样本。

ar1 = np.linspace(2.0, 3.0, num=5)
ar2 = np.linspace(2.0, 3.0, num=5, endpoint=False)
ar3 = np.linspace(2.0, 3.0, num=5, retstep=True)
print(ar1,type(ar1))
print(ar2)
print(ar3,type(ar3))
# numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
# start:起始值,stop:结束值
# num:生成样本数,默认为50
# endpoint:如果为真,则停止是最后一个样本。否则,不包括在内。默认值为True。
# retstep:如果为真,返回(样本,步骤),其中步长是样本之间的间距 → 输出为一个包含2个元素的元祖,第一个元素为array,第二个为步长实际值

 

# 创建数组:zeros()/zeros_like()/ones()/ones_like()

ar1 = np.zeros(5)  
ar2 = np.zeros((2,2), dtype = np.int)
print(ar1,ar1.dtype)
# numpy.zeros(shape, dtype=float, order='C'):返回给定形状和类型的新数组,用零填充。
# shape:数组纬度,二维以上需要用(),且输入参数为整数
# dtype:数据类型,默认numpy.float64
# order:是否在存储器中以C或Fortran连续(按行或列方式)存储多维数据。
# 返回具有与给定数组相同的形状和类型的零数组,这里ar4根据ar3的形状和dtype创建一个全0的数组

ar5 = np.ones(9)
ar6 = np.ones((2,3,4))

# ones()/ones_like()和zeros()/zeros_like()一样,只是填充为1

 

# 创建数组:eye()

print(np.eye(5))
# 创建一个正方的N*N的单位矩阵,对角线值为1,其余为0

 

 

ndarray的数据类型

bool 用一个字节存储的布尔类型(True或False)

inti 由所在平台决定其大小的整数(一般为int32或int64)

int8 一个字节大小,-128 至 127

int16 整数,-32768 至 32767

int32 整数,-2 ** 31 至 2 ** 32 -1

int64 整数,-2 ** 63 至 2 ** 63 - 1

uint8 无符号整数,0 至 255

uint16 无符号整数,0 至 65535

uint32 无符号整数,0 至 2 ** 32 - 1

uint64 无符号整数,0 至 2 ** 64 - 1

float16 半精度浮点数:16位,正负号1位,指数5位,精度10位

float32 单精度浮点数:32位,正负号1位,指数8位,精度23位

float64或float 双精度浮点数:64位,正负号1位,指数11位,精度52位

complex64 复数,分别用两个32位浮点数表示实部和虚部

complex128或complex 复数,分别用两个64位浮点数表示实部和虚部

 

 

核心:基本索引及切片 / 布尔型索引及切片

ar = np.arange(20)
print(ar)
print(ar[4])
print(ar[3:6])
print('-----')
# 一维数组索引及切片

ar = np.arange(16).reshape(4,4)
print(ar, '数组轴数为%i' %ar.ndim)   # 4*4的数组
print(ar[2],  '数组轴数为%i' %ar[2].ndim)  # 切片为下一维度的一个元素,所以是一维数组
print(ar[2][1]) # 二次索引,得到一维数组中的一个值
print(ar[1:3],  '数组轴数为%i' %ar[1:3].ndim)  # 切片为两个一维数组组成的二维数组
print(ar[2,2])  # 切片数组中的第三行第三列 → 10
print(ar[:2,1:])  # 切片数组中的1,2行、2,3,4列 → 二维数组
print('-----'

 

                             numpy.random包含多种概率分布的随机样本,是数据分析辅助的重点工具之一

# 随机数生成

samples = np.random.normal(size=(4,4))
print(samples)
# 生成一个标准正太分布的4*4样本值

 

# numpy.random.rand(d0, d1, ..., dn):生成一个[0,1)之间的随机浮点数或N维浮点数组 —— 均匀分布

import matplotlib.pyplot as plt  # 导入matplotlib模块,用于图表辅助分析
% matplotlib inline
# 魔法函数,每次运行自动生成图表

a = np.random.rand()
print(a,type(a))  # 生成一个随机浮点数

b = np.random.rand(4)
print(b,type(b))  # 生成形状为4的一维数组

c = np.random.rand(2,3)
print(c,type(c))  # 生成形状为2*3的二维数组,注意这里不是((2,3))

samples1 = np.random.rand(1000)
samples2 = np.random.rand(1000)
plt.scatter(samples1,samples2)
# 生成1000个均匀分布的样本值

 

#  numpy.random.randn(d0, d1, ..., dn):生成一个浮点数或N维浮点数组 —— 正态分布

samples1 = np.random.randn(1000)
samples2 = np.random.randn(1000)
plt.scatter(samples1,samples2)
# randn和rand的参数用法一样
# 生成1000个正太的样本值

 

# numpy.random.randint(low, high=None, size=None, dtype='l'):生成一个整数或N维整数数组
# 若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数,且high必须大于low
# dtype参数:只能是int类型  

print(np.random.randint(2))
# low=2:生成1个[0,2)之间随机整数  

print(np.random.randint(2,size=5))
# low=2,size=5 :生成5个[0,2)之间随机整数

print(np.random.randint(2,6,size=5))
# low=2,high=6,size=5:生成5个[2,6)之间随机整数  

print(np.random.randint(2,size=(2,3)))
# low=2,size=(2,3):生成一个2x3整数数组,取数范围:[0,2)随机整数

print(np.random.randint(2,6,(2,3)))
# low=2,high=6,size=(2,3):生成一个2*3整数数组,取值范围:[2,6)随机整数 

 

# 随机种子    就是每次的随机数字都会发生变化,用这个呢   就可保留随机的值
# 计算机实现的随机数生成通常为伪随机数生成器,为了使得具备随机性的代码最终的结果可复现,需要设置相同的种子值

rng = np.random.RandomState(1)  
xtrain = 10 * rng.rand(30)
ytrain = 8 + 4 * xtrain + rng.rand(30)
# np.random.RandomState → 随机数种子,对于一个随机数发生器,只要该种子(seed)相同,产生的随机数序列就是相同的
# 生成随机数据x与y
# 样本关系:y = 8 + 4*x

fig = plt.figure(figsize =(12,3))
ax1 = fig.add_subplot(1,2,1)
plt.scatter(xtrain,ytrain,marker = '.',color = 'k')
plt.grid()
plt.title('样本数据散点图')
# 生成散点图

 

数组形状改变(3种)

# 数组形状:.T/.reshape()/.resize()

# .T方法:转置,例如原shape为(3,4)/(2,3,4),转置结果为(4,3)/(4,3,2) → 所以一维数组转置后结果不变

# numpy.reshape(a, newshape, order='C'):为数组提供新形状,而不更改其数据,所以元素数量需要一致!!

# numpy.resize(a, new_shape):返回具有指定形状的新数组,如有必要可重复填充所需数量的元素。
# 注意了:.T/.reshape()/.resize()都是生成新的数组!!!

 

ar3 = ar1.copy()
print(ar3 is ar1)
ar1[0] = 9
print(ar1,ar3)
# copy方法生成数组及其数据的完整拷贝
# 再次提醒:.T/.reshape()/.resize()都是生成新的数组!!!

 

# 数组类型转换:.astype()

ar1 = np.arange(10,dtype=float)
print(ar1,ar1.dtype)
print('-----')
# 可以在参数位置设置数组类型

ar2 = ar1.astype(np.int32)
print(ar2,ar2.dtype)
print(ar1,ar1.dtype)
# a.astype():转换数组类型
# 注意:养成好习惯,数组类型用np.int32,而不是直接int32

 

# 数组堆叠

a = np.arange(5)    # a为一维数组,5个元素
b = np.arange(5,9) # b为一维数组,4个元素
ar1 = np.hstack((a,b))  # 注意:((a,b)),这里形状可以不一样
print(a,a.shape)
print(b,b.shape)
print(ar1,ar1.shape)
a = np.array([[1],[2],[3]])   # a为二维数组,3行1列
b = np.array([['a'],['b'],['c']])  # b为二维数组,3行1列
ar2 = np.hstack((a,b))  # 注意:((a,b)),这里形状必须一样
print(a,a.shape)
print(b,b.shape)
print(ar2,ar2.shape)
print('-----')
# numpy.hstack(tup):水平(按列顺序)堆叠数组

a = np.arange(5)    
b = np.arange(5,10)
ar1 = np.vstack((a,b))
print(a,a.shape)
print(b,b.shape)
print(ar1,ar1.shape)
a = np.array([[1],[2],[3]])   
b = np.array([['a'],['b'],['c'],['d']])   
ar2 = np.vstack((a,b))  # 这里形状可以不一样
print(a,a.shape)
print(b,b.shape)
print(ar2,ar2.shape)
print('-----')
# numpy.vstack(tup):垂直(按列顺序)堆叠数组

a = np.arange(5)    
b = np.arange(5,10)
ar1 = np.stack((a,b))
ar2 = np.stack((a,b),axis = 1)
print(a,a.shape)
print(b,b.shape)
print(ar1,ar1.shape)
print(ar2,ar2.shape)
# numpy.stack(arrays, axis=0):沿着新轴连接数组的序列,形状必须一样!
# 重点解释axis参数的意思,假设两个数组[1 2 3]和[4 5 6],shape均为(3,0)
# axis=0:[[1 2 3] [4 5 6]],shape为(2,3)
# axis=1:[[1 4] [2 5] [3 6]],shape为(3,2)

 

# 数组拆分

ar = np.arange(16).reshape(4,4)
ar1 = np.hsplit(ar,2)
print(ar)
print(ar1,type(ar1))
# numpy.hsplit(ary, indices_or_sections):将数组水平(逐列)拆分为多个子数组 → 按列拆分
# 输出结果为列表,列表中元素为数组

ar2 = np.vsplit(ar,4)
print(ar2,type(ar2))
# numpy.vsplit(ary, indices_or_sections)::将数组垂直(行方向)拆分为多个子数组 → 按行拆

 

# 数组简单运算

ar = np.arange(6).reshape(2,3)
print(ar + 10)   # 加法
print(ar * 2)   # 乘法
print(1 / (ar+1))  # 除法
print(ar ** 0.5)  # 幂
# 与标量的运算

print(ar.mean())  # 求平均值
print(ar.max())  # 求最大值
print(ar.min())  # 求最小值
print(ar.std())  # 求标准差
print(ar.var())  # 求方差
print(ar.sum(), np.sum(ar,axis = 0))  # 求和,np.sum() → axis为0,按列求和;axis为1,按行求和
print(np.sort(np.array([1,4,3,2,5,6])))  # 排序
# 常用函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值