pandas 01 预备知识

# 1 列表推导式

# 01 列表推导式生成数字序列

# 02 列表推导式的多层嵌套

# 03 列表推导式+条件赋值value = a if condition else b

# 04 列表推导式+匿名函数map

# 2 打包

# 01 zip

# 001 用zip建立字典映射

# 002 解压

# 02 enumerate

# 3 np构造数组

# 01 等差

# 02 特殊

# 03 随机 np.random

# 001 0-1均匀分布的随机数组 np.random.rand

# 002 标准正态分布随机数组 np.random.randn

# 003 随机整数组 np.random.randint

# 004 从给定列表中抽样 np.random.choice

# 005 乱序原列表 np.random.permutation

# 006 随机种子 固定随机数输出结果

# 4 np数组的变形与合并

# 01 转置

# 02 合并

# 03 维度变换

# 5 np数组的切片与索引

# 01 slice类型的start:end:step切片

# 02 np.ix_ 对应维度使用布尔索引

# 6 一维数组常用函数

# 01 返回索引

# 02 计算

# 03 统计

# 04 协方差 相关系数

# 7 广播机制

# 01 标量+数组:标量自动扩充为数组大小

# 02 二维数组之间

# 03 一维数组与二维数组:把一维数组视为1,k

# 8 向量与矩阵的计算

# 01 向量内积dot

# 02 矩阵乘法

# 1 列表推导式
# 01 列表推导式生成数字序列
L = []
def my_func(x):
    return x*2

for i in range(5):
    L.append(my_func(i))

L = [my_func(i) for i in range(5)]
L
# 02 列表推导式的多层嵌套
# 第一个for是外层循环,第二个for是内层循环
[m+'_'+n for m in ['a','b'] for n in ['c','s']]
# 03 列表推导式+条件赋值value = a if condition else b
L = [1, 2, 3, 4, 5, 6, 7]
[i if i<=5 else 'Q' for i in L]
# 04 列表推导式+匿名函数map
my_func = lambda x: 2*x
my_func(3)
[(lambda x: 2*x)(i) for i in range(5)]
[my_func(i) for i in range(5)]

list(map(my_func, range(5)))
list(map(lambda x,y:str(x)+'_'+str(y), range(5),list('abcds')))

# 2 打包
# 01 zip
l1,l2,l3 = list('abc'), list('123'), list('456')
list(zip(l1,l2,l3))
tuple(zip(l1,l2,l3))

for i,j,k in zip(l1,l2,l3):
    print(i,j,k)
# 001 用zip建立字典映射
dict(zip(l1,l2))
# 002 解压
zipped = list(zip(l1,l2,l3))
zipped
list(zip(*zipped))
# 02 enumerate
l = list('abcd')
for index, value in enumerate(l):
    print(index,value)
for index, value in zip(range(len(l)), l):
    print(index, value)
    
    
# 3 np构造数组
import numpy as np
np.array([1, 2, 3])
# 01 等差
np.linspace(5,10,6) #起始,终止,个数,左闭右闭
np.arange(5,10,2) #起始,终止,步长,左闭右开
# 02 特殊
np.zeros((2,3)) #2*3小数点的零矩阵
np.ones((3,1))
np.eye(3) #3*3单位阵
np.eye(4, k=1) #4*4主对角线向右偏移1个单位的伪单位阵
np.full((2,3), 10) #2*3,元素全是10
np.full((2,4), [1,2,3,4]) #列表传入列的值 元素个数=列值
# 03 随机 np.random
# 001 0-1均匀分布的随机数组 np.random.rand
np.random.rand(3) #生成3个服从0-1均匀分布的随机数
np.random.rand(3,2) # 3个列表,每个列表里面2个数 
# a-b均匀分布的随机数组
(b - a) * np.random.rand(3) + a
# 002 标准正态分布随机数组 np.random.randn
np.random.randn(2)
np.random.randn(3,2)
# 正态分布随机数组
sigma, mu = 2.5, 3
mu + np.random.randn(5) * sigma
# 003 随机整数组 np.random.randint
low, high, size = 5, 15, (2, 2)
np.random.randint(low, high, size)
# 004 从给定列表中抽样 np.random.choice
list = ['a', 'b', 'c', 'd']
# repalce是否为放回抽样, p=[0.1, 0.1, 0.7, 0.1]不指定概率时为均匀抽样
np.random.choice(list, 5, replace=False, p=[0.1, 0.1, 0.7, 0.1])
np.random.choice(list, (3,3)) #replace默认为True,放回抽样
# 005 乱序原列表 np.random.permutation
np.random.permutation(list)
# 006 随机种子 固定随机数输出结果
np.random.seed(0)
np.random.rand()

# 4 np数组的变形与合并
# 01 转置
np.zeros((2,3)).T
# 02 合并
# 多维+多维
np.r_[np.zeros((2,3)),np.ones((1,3))] # 按行合并,列数相同
np.c_[np.eye(2),np.full((2,1),[5])] # 按列合并,行数相同
# 多维+一维
# 一维数组看作列向量,行数相同
np.c_[np.linspace(1,5,3),np.zeros((3,2))] 
np.c_[np.array([0,0]),np.ones((2,5))]
# 一维+一维
np.r_[np.array([0,0]),np.zeros(2)]
# 03 维度变换
target = np.arange(8).reshape(2,4)
target
target.reshape((4,2), order='C') # 按行读取和填充
target.reshape((4,2), order='F') # 按列读取和填充
target.reshape((4,-1)) # 默认按行,允许一个维度存在空缺,填充-1

target = np.ones((3,1))
target
target.reshape(-1) # n*1转为1*n

# 5 np数组的切片与索引
# 01 slice类型的start:end:step切片
target = np.arange(9).reshape(3,3)
target[:-1,[0,2]]
# 02 np.ix_ 对应维度使用布尔索引
target[np.ix_([True,False,True],[True,False,True])]
target[np.ix_([0,2],[True,False,True])]
# 一维数组可直接进行布尔索引,无需np.ix_
new = target.reshape(-1)
new[new%2==0]

# 06 一维数组常用函数
# where 
a = np.arange(8)
np.where(a%2==0, a, 'Q')
# 返回索引
np.nonzero(a) # 返回非零索引
a.argmax() # 返回最大值索引
a.argmin() # 返回最小值索引
# any,all
b = np.array([0,1])
b.any() # 至少存在一个True或非零元素时返回True
b.all() # 全部为True或非零元素时返回True
# 计算
c = np.array([1,2,3])
c.cumprod() # 累乘
c.cumsum() # 累加
np.diff(c) #和前一个元素做差,长度-1
# 统计
c.max() # max,min,mean,median,std,var,sum
np.quantile(c, 0.5) #分位数
np.median(c,axis=0)
# 对于含有缺失值的数组,以上函数会返回缺失值
np.nanmax(c)
np.nanquantile(c, 0.5)
# 协方差 相关系数
t1 = np.array([1,2,3])
t2 = np.array([-1,5,8])
np.cov(t1,t2)
np.corrcoef(t1,t2)
# 二维 0列1行
t = np.arange(1,9).reshape(4,-1)
t
t.sum(0) # 列和
t.sum(1) # 行和

# 07 广播机制
# 标量+数组:标量自动扩充为数组大小
res = 3 * np.ones((2,2)) + 1
res = 1 / res
# 二维数组之间
res = np.ones((3,2))
res
res * np.array([2,3]) # 把第一维扩充为3,第二维仍是2
res * np.array([[4],[5],[6]]) # 把第二维扩充为2
res * np.array([[2]]) #把第一维扩充为3,第二维扩充为2
# 一维数组与二维数组:把一维数组视为1,k
np.ones(3) + np.ones((2,3))  #1,3 + 2,3 → 2,3
np.ones(3) + np.ones((3,1))  #1,3 + 3,1 → 3,3
np.ones(1) + np.ones((2,3))  #1,1 + 2,3 → 2,3

# 08 向量与矩阵的计算
# 向量内积dot
a = np.array([1,2,3])
b = np.array([1,3,5])
a.dot(b)
# 矩阵乘法
a = np.arange(4).reshape(-1,2)
b = np.arange(-4,0).reshape(-1,2)
a@b

# Ex1 用列表推导式写矩阵乘法
# A.
M1 = np.random.randint(1,5,(2,3))
M2 = np.random.randint(1,5,(3,3))
res = np.empty((M1.shape[0],M2.shape[1]))
for i in range(M1.shape[0]):
    for j in range(M2.shape[1]):
        item = 0
        for k in range(M1.shape[1]):
            item += M1[i][k] * M2[k][j]
        res[i][j] = item
M1,M2,res 
((M1@M2 - res) < 1e-15).all()
# B.
# sum([M1[0][k] * M2[k][0] for k in range(M1.shape[1])])
[[sum([M1[i][k] * M2[k][j] for k in range(M1.shape[1])]) 
  for j in range(M2.shape[1])] 
 for i in range(M1.shape[0])]

# Ex2 更新矩阵
A = np.arange(1,10).reshape(3,3)
# a = [(sum(1/A[i][j] for j in range(A.shape[1]))) for i in range(A.shape[0])]
B = A * a
B = A*(1/A).sum(1).reshape(-1,1)

# Ex3 卡方统计量
np.random.seed(0)
A = np.random.randint(10, 20, (8,5))
# B = [[(A.sum(1)[i] * A.sum(0)[j]) / sum(A.sum(0)) for j in range(A.shape[1])] for i in range(A.shape[0])]
B = A.sum(0)*A.sum(1).reshape(-1, 1)/A.sum()
res = ((A - B) ** 2 / B).sum()

# Ex4 改进矩阵计算的性能
np.random.seed(0)
m, n, p, = 2, 3, 4
B = np.random.randint(0,2,(m,p))
U = np.random.randint(0,2,(p,n))
Z = np.random.randint(0,2,(m,n))
B, U, Z
# A.
(B[0,:] - U[:,0]).dot(B[0,:] - U[:,0]) * Z[0,0]
sum = 0

for i in range(m):
    for j in range(n):
        sum += (B[i,:] - U[:,j]).dot(B[i,:] - U[:,j]) * Z[i,j]
sum
# B.
def solution(B=B, U=U, Z=Z):
    L_res = []
    sum = 0
    for i in range(m):
        for j in range(n):
            norm_value = ((B[i] - U[:,j])**2).sum()
            L_res.append(norm_value * Z[i][j])
            sum += norm_value * Z[i][j]
    return L_res,sum
solution(B, U, Z)
%timeit -n 30 solution(B, U, Z)
# C.
(((B**2).sum(1).reshape(-1,1) + (U**2).sum(0) - 2*B@U)*Z).sum()
%timeit -n 30 ((np.ones((m,n))*(B**2).sum(1).reshape(-1,1) + np.ones((m,n))*(U**2).sum(0) - 2*B@U)*Z).sum()

# Ex5 连续整数的最大长度
# A.
l = [3,2,1,2,3,4,6]
np.diff([0]+np.nonzero(np.diff(l)-1)[0].tolist()+[len(np.diff(l))-1]).max()
np.diff(np.nonzero([1]+(np.diff(l)-1).tolist()+[1])[0].tolist()).max()
# B.
f = lambda x: np.diff(np.nonzero(np.r_[1,np.diff(l)!=1,1])).max()
f([3,2,1,2,3,4,6])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值