查看pandas版本
pandas需要大于1.1
import pandas as pd
pd.__version__
'1.1.5'
py基础
1.列表推导式与条件赋值
- 生成数字序列,如下:
L = []
def my_func(x):
return 2*x
for i in range(5):
L.append(my_func(i))
L
[0, 2, 4, 6, 8]
对以上写法进行简化:
[* for i in *]
- 第一个*为映射函数
- 第二个表示迭代对象
[my_func(i) for i in range(5)]
L
[0, 2, 4, 6, 8]
- 列表支持多层嵌套
- 第一个for为外层循环
- 第二个for为内层循环
[m+'_'+n for m in ['a','b'] for n in ['c','d']]
['a_c', 'a_d', 'b_c', 'b_d']
- 实用的语法糖,
value = a if condition else b
value = 'cat' if 2>1 else 'dog'
value
# cat
a, b = 'cat','dog'
condition = 2>1
if condition:
value = a
else:
value = b
value
'cat'
- 截断列表中超过5的元素
- 超过5用15代替
- 小于5保留原来的值
L = [1,2,3,4,5,6,7]
[i if i <= 5 else 5 for i in L]
[1, 2, 3, 4, 5, 5, 5]
2.匿名函数与map方法
- 匿名函数,映射关系
my_func = lambda x: 2*x
my_func(3)
# 6
multi_para_func = lambda a, b: a + b
multi_para_func(1,2)
3
- 只关心映射关系
[(lambda x:2*x)(i) for i in range(5)]
[0, 2, 4, 6, 8]
- map函数实现匿名函数映射
- 返回值为
map
对象 - 需要通过
list
转为列表
- 返回值为
list(map(lambda x :2*x, range(5)))
[0, 2, 4, 6, 8]
map(lambda x:2*x, range(5))
# map(function, iterable, ...)
# map() 会根据提供的函数对指定序列做映射。
# 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
<map at 0x7ff8ac588b90>
- 多个输入值的函数映射,追加迭代对象
list(map(lambda x, y: str(x)+'_'+y, range(5),list('abcde')))
['0_a', '1_b', '2_c', '3_d', '4_e']
3.zip对象与enumerate方法
- zip函数把多个可迭代对象打包为一个元组构成的可迭代对象
- 返回zip对象
- 通过tuple,list可得到打包结果
L1,L2,L3 = list('abc'),list('def'),list('hij')
list(zip(L1,L2,L3))
# [('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j')]
tuple(zip(L1,L2,L3))
# (('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j'))
(('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j'))
- 循环迭代使用zip函数
for i,j,k in zip(L1,L2,L3):
print(i,j,k)
a d h
b e i
c f j
enumerate
是一种特殊的打包,迭代时绑定迭代元素遍历序号
L = list('abcd')
for index,value in enumerate(L):
print(index,value)
0 a
1 b
2 c
3 d
- zip对象也可实现
for index,value in zip(range(len(L)),L):
print(index,value)
0 a
1 b
2 c
3 d
- 对2个列表字典建立映射
dict(zip(L1,L2))
{'a': 'd', 'b': 'e', 'c': 'f'}
- 使用
*
和zip
联合使用解压
zipped = list(zip(L1,L2,L3))
zipped
[('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j')]
# 三个元组分别对应原来的列表
list(zip(*zipped))
[('a', 'b', 'c'), ('d', 'e', 'f'), ('h', 'i', 'j')]
Numpy基础
1.np数组的构造
- 一般用
array
来构造
import numpy as np
np.array([1,2,3])
array([1, 2, 3])
- 等差序列
np.linspace
np.arange
np.linspace(1,10,5) # 起始、终止(包含)、样本个数
array([ 1. , 3.25, 5.5 , 7.75, 10. ])
np.arange(1,10,2) # 起始、终止(不包含)、步长
array([1, 3])
- 特殊矩阵
- zeros
- eye
- full
np.zeros((2,3)) # 传入【元组】表示各维度大小
array([[0., 0., 0.],
[0., 0., 0.]])
np.eye(3) # 3*3的单位矩阵
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
np.eye(3,k=1) # 偏移主对角线1个单位的伪单位矩阵
array([[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.]])
np.full((2,3),10) # 元组表示传入大小,10表示填充数值
array([[10, 10, 10],
[10, 10, 10]])
np.full((2,3),[1,2,3]) # 通过传入列表填充每列的值
array([[1, 2, 3],
[1, 2, 3]])
np.full([3,2],(2,3))
array([[2, 3],
[2, 3],
[2, 3]])
- 随机矩阵
rand
,0-1均匀分布的随机数组randn
,标准正态的随机数组randint
,随机整数组choice
,随机列表抽样
np.random.rand(3) # 生成服从0-1均匀分布的3个随机数
array([0.61990912, 0.54366886, 0.87244518])
np.random.rand(3, 4) # 这里传入的不是元组,每个维度大小分开输入
array([[0.42896824, 0.91257234, 0.83238299, 0.77677523],
[0.76413901, 0.04422387, 0.6099136 , 0.45875961],
[0.48164369, 0.96835974, 0.76983916, 0.70918709]])
# 服从a到b上的均匀分布
a, b = 5, 15
(b - a) * np.random.rand(3) + a
array([8.5273887 , 6.29358181, 9.43011693])
- 生成N(0,1)的标准正态分布
np.random.randn(3)
array([-1.13797816, -2.02967111, 0.34273311])
np.random.randn(2,2)
array([[-1.39158366, 0.38447267],
[-1.54725737, 0.36205205]])
- 服从方差为均值为的一元正态分布可以如下生成:
sigma, mu = 2.5, 3
mu + np.random.randn(3) * sigma
array([6.17817581, 3.70266801, 1.74245868])
randint
生成随机整数的最小值最大值(不包含),维度大小
low, high, size = 5, 15, (2,2) # 最小值、最大值(不包含)、维度
np.random.randint(low, high, size)
array([[12, 7],
[ 7, 14]])
choice
可以从给定的列表中,以一定概率和方式抽取结果,当不指定概率时为均匀采样,默认为有放回抽样
my_list = ['a','b','c','d']
np.random.choice(my_list, 2, replace=False, p=[0.1,0.7,0.1,0.1])
array(['b', 'd'], dtype='<U1')
np.random.permutation(my_list)
array(['c', 'd', 'b', 'a'], dtype='<U1')
- seed,固定随机数输出结果
np.random.seed(0)
np.random.rand()
0.5488135039273248
np.random.seed(0)
np.random.rand()
0.5488135039273248
数组的变形与合并
- 转置
np.zeros((2,3)).T
array([[0., 0.],
[0., 0.],
[0., 0.]])
- 合并操作
r_
:上下合并c_
:左右合并
# 上下合并
np.r_[np.zeros((2,3)),np.zeros((2,3))]
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
# 左右合并
np.c_[np.zeros((2,3)),np.zeros((2,3))]
array([[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]])
np.zeros((2,3))
array([[0., 0., 0.],
[0., 0., 0.]])
np.c_[np.array([0,0]),np.zeros((2,3))]
array([[0., 0., 0., 0.],
[0., 0., 0., 0.]])
- 维度变换:
reshape
target = np.arange(8).reshape(2,4)
target
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
target.reshape((4,2),order='C') # 按照行读取和填充
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])
target.reshape((4,2),order='F') # 按照列进行读取和传输
array([[0, 2],
[4, 6],
[1, 3],
[5, 7]])
target.reshape((4,-1))
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])
3.np数组切片与索引
- 数组的切片模式支持使用
slice
类型的start:end:step
切片
target = np.arange(9).reshape(3,3)
target
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
target[:-1,[0,2]]
array([[0, 2],
[3, 5]])
target[:2,[0,2]]
array([[0, 2],
[3, 5]])
target[0:2]
array([[0, 1, 2],
[3, 4, 5]])
numpy切片补充
:
用以表示当前维度的所有子模块a[1:]
表示该列表中的第1个元素到最后一个元素,而,a[:n]
表示从第0个元素到第n个元素(不包括n)-1
用以表示当前维度所有子模块最后一个,负号用以表示从后往前数的元素,-n
即是表示从后往前数的第n个元素
target[:-1] # 所有行,到最后一行,不包括最后一行
array([[0, 1, 2],
[3, 4, 5]])
target[-2:] # 倒3行,也就是倒数第2行开始,一直到最后一行
array([[3, 4, 5],
[6, 7, 8]])
target[:,-1:] # 所有行,倒1列
array([[2],
[5],
[8]])
- 利用
np.ix_
在对应的维度上使用布尔索引,但此时不能使用slice
切片
target[np.ix_([True,False,True],[True,False,True])]
array([[0, 2],
[6, 8]])
target[np.ix_([1,2],[True,False,True])]
array([[3, 5],
[6, 8]])
new = target.reshape(-1)
new[new%2==0]
# new[new%2==0]
array([0, 2, 4, 6, 8])
4.常用函数
where
a = np.array([-1,1,-1,0])
np.where(a>0,a,5)
array([5, 1, 5, 5])
nonzero
:返回非零数索引argmax
:最大数argmin
:最小数
a = np.array([-2,-5,0,1,3,-1])
np.nonzero(a)
(array([0, 1, 3, 4, 5]),)
a.argmax()
4
a.argmin()
# 1
any
,all
any
指当序列至少存在一个True或非零元素时返回True,否则返回falseall
指当序列元素全为True或非零元素时返回True,否则返回false
cumprod
,cumsum
分别表示累乘和累加函数,返回同长度的数组diff
表示和前一个元素做差,由于第一个元素为缺失值,因此在默认参数情况下,返回长度是原数组减1
a = np.array([1,2,3])
a.cumprod()
# 1 2 3
# 1 2
# 1
array([1, 2, 6])
a.cumsum()
# 1 2 3
# 1 2
# 1
array([1, 3, 6])
np.diff(a)
array([1, 1])
- 统计函数
max
,min
,mean
,median
,std
,var
,sum
,quantile
target = np.arange(5)
target
array([0, 1, 2, 3, 4])
target.max()
4
np.quantile(target, 0.5) # 0.5分位数
2.0
target = np.array([1, 2, np.nan])
target
array([ 1., 2., nan])
target.max()
nan
np.nanmax(target)
2.0
np.nanquantile(target,0.5)
1.5
target1 = np.array([1,3,5,9])
target2 = np.array([1,5,3,-9])
np.cov(target1, target2)
array([[ 11.66666667, -16.66666667],
[-16.66666667, 38.66666667]])
np.corrcoef(target1,target2)
array([[ 1. , -0.78470603],
[-0.78470603, 1. ]])
- 其中0代表列的计算,1代表行的计算,即对列和行分别累积求和、 积。
target = np.arange(1, 10).reshape(3,-1)
target
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
target.sum(0)
array([12, 15, 18])
target.sum(1)
array([ 6, 15, 24])
5.广播机制
- 标量和数组操作
res = 3 * np.ones((2,2)) + 1
res
array([[4., 4.],
[4., 4.]])
res = 1/res
res
array([[0.25, 0.25],
[0.25, 0.25]])
- 二维数组操作
res = np.ones((3,2))
res
array([[1., 1.],
[1., 1.],
[1., 1.]])
res * np.array([[2,3]]) # 3*2 1*2 >> 3*2
# new array
# 1 1 * 2 3
# 1 1 * 2 3
# 1 1 * 2 3
array([[2., 3.],
[2., 3.],
[2., 3.]])
res * np.array([[2],[3],[2]]) # 扩充第二维度
# new array
# 1 1 * 2 1
# 1 1 * 3 1
# 1 1 * 2 1
array([[2., 2.],
[3., 3.],
[2., 2.]])
res * np.array([[2]])
# new array
# 1 1 * 2 1
# 1 1 * 2 1
# 1 1 * 2 1
array([[2., 2.],
[2., 2.],
[2., 2.]])
- 1维数组和2维数组
np.ones(3) + np.ones((2,3)) # 1*3 2*3 >> 2*3
array([[2., 2., 2.],
[2., 2., 2.]])
np.ones(3) + np.ones((2,1)) # 1*3 2*1 >> 2*3
array([[2., 2., 2.],
[2., 2., 2.]])
np.ones(1) + np.ones((2,3)) # 1*1 2*3 >> 2*3
array([[2., 2., 2.],
[2., 2., 2.]])
6.向量和矩阵的计算
- 向量内积:
dot
a = np.array([1,2,3])
b = np.array([1,3,5])
a.dot(b)
22
- 向量范数和矩阵范数:
ng.linalg.norm
a = np.arange(4).reshape(-1,2)
a
array([[0, 1],
[2, 3]])
np.linalg.norm(a,np.inf)
5.0
np.linalg.norm(a,'fro')
3.7416573867739413
np.linalg.norm(a,1) # 列和最大值
4.0
np.linalg.norm(a,1)
4.0
b = np.arange(4)
b = np.linalg.norm(a,1)
b
4.0
- 矩阵乘法
a = np.arange(4).reshape(-1,2)
a
array([[0, 1],
[2, 3]])
b = np.arange(-4,0).reshape(-1,2)
b
array([[-4, -3],
[-2, -1]])
a@b
array([[ -2, -1],
[-14, -9]])
参考自:DATAWHALE组队学习