Numpy
Numpy是高性能科学计算和数据分析的基础包,
Pandas是对它的更高级的封装
import numpy ''' NumPy的主要对象是ndarray,该对象是一个快速、灵活的大数据容器。 它与python中的list,turple不同;它所存储的数据类型必须相同。 ''' # 多维数组 data = [1, 2, 3, 4] arr1 = numpy.array(data) print(arr1, type(arr1)) # [1 2 3 4] <class 'numpy.ndarray'> print(numpy.zeros((3, 3),dtype='int')) print(numpy.ones((3, 3))) print(numpy.arange(1, 10, 0.2)) # 1-10差为0.2 的等差序列 print(numpy.linspace(1, 10, 4))
np.empty(100) 只申请100个地址,原内存里的值并没有清空 arr4 = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) arr4[:2, :2] = 10 print(arr4) # 再将一个标量赋值给一个切片时,该值会被广播到整个切片视图上,并直接对原数组进行修改,如果想避免改变原数据,可以使用copy函数 arr4.copy()[:2, :2] = 5 # 基本的数组运算 # arr4+arr4 # arr4*arr4 # arr4*2 # arr4**0.5
# arr4+1
# 3/arr4 # arr4.sum()
arr4.std()
arr4.mean() # 算数平均数
arr4.max()
print(arr4.argmin()) # 最大索引值
arr4.argmax()
arr4.cumsum() # 所有元素的累计和
arr4.cumprod() # 所有元素的累计积
arr.size 最小元素的个数
arr.dtype 元素的类型
arr.astype(float) #转换类型
arr.shape
arr.reshape((x,y))
arr.T 转置
arr.ndim 几维数组
python的数组切片后 是一个新的 而numpy是对原数据的引用

# 生成3行2列值{0,1)的随机多维数组
# print(numpy.random.rand(3, 2)) # 几个参数就是几维
'''
函数 参数 描述
rand d0,d1...dn 生成半开区间[0,1)内的多位随机数
randn d0,d1...dn 生成来自标准正态分布的多个样本
randint low[,high,size] 生成版开区间[low,high)内的随机整数;size是有几个
choice a[,size,replace,p] 生成在给定的一维数组中的随机样本
bytes length 生成随机字符串
'''
import matplotlib.pyplot as plt
size = 1000
rn1 = numpy.random.rand(size,2)
rn2 = numpy.random.randn(size)
rn3= numpy.random.randint(0,10,size)
rang = [0,10,20,30,40]
rn4 = numpy.random.choice(rang,size=size)
fig,((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows=2,ncols=2,figsize=(10,10))
ax1.hist(rn1,bins=25,stacked=True)
ax1.set_title('rand')
ax1.set_ylabel('frequency')
ax1.grid(True)
ax2.hist(rn2,bins=25)
ax2.set_title('randn')
ax2.grid(True)
ax3.hist(rn3,bins=25 )
ax3.set_title('randint')
ax3.grid(True)
ax4.hist(rn4,bins=25 )
ax4.set_title('choice')
ax4.grid(True)
fig.show()
numpy.random.binomial(100, 0.3, 1000) # n=100,p=0.3的二项分布 numpy.random.normal(10, 20, 1000) # 均值为10,标准差为20的正态分布 numpy.random.chisquare(0.5, 1000) # 自由度为0.5的卡方分布 numpy.random.poisson(2.0, 1000) # λ为2的泊松分布


布尔型索引


a[(a>5)&(a%2==0)] # and的意思,但这里要用 &(位运算符) # 因为这里的& 作用被重载了 a[(a>5)|(a%2==0)]
True and False # False
True & False # False
3 and 5 # 5
3 & 1 # 0 # 位运算优先级高
花式索引

a[,] ,左边行 右边列
左右两边 可以是具体的值,也可以是布尔型索引,也可以是花式索引

通用函数
一元函数
numpy提供的
abs(数组) # 原生的可以 ,np的可以 sqrt # 原生的不可以 ,np的可以
exp
log
ceil(数组) # 向上取整
floor(数组) # 向下取整
round(数组) # 四舍五入
trunc(数组) # 向0取整
rint(数组) # 向0取整
modf(数组) # 把整数部分和小数部分分开
isnan # b中每个元素是不是nan 返回True\False的数组
np.nan(b)
~np.nan(b) 取反 # 和 & | 一样
isinf
cos sin tan
nan float('nan' ) # not a number inf float('ini') 0.0/0.0 nan
5 /0 inf # 无穷大 np.nan == np.nan # False np.nan is np.nan # True
np.inf == np.inf # True
原生的
int 向0取整 round 四舍五入 math.ceil 向上取整 math.floor 向下取整
二元函数
add substract multiply divide power mod
a.mean() # 平均值 np.maximum(a,b) 每一位比较取大的重新构成数组
mininum
a.var() # 方差 (xi-x)^2 求和 /n # 离散程度
a.std() # 标准差 根号方差 #
a.min()
a.max()
a.argmin() # 最大值的下表
a.argmax()
random



都被重写,支持了批量生成数据的功能


浙公网安备 33010602011771号