Pandas学习_task 01预备知识

这篇博客主要介绍了Pandas学习的基础,包括Python的列表推导式、匿名函数、zip对象与enumerate方法,以及Numpy的数组构造、切片与索引、广播机制等,并给出了相关练习题,旨在提升对Python和Numpy的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习目标:

一个月掌握 Pandas入门与实践

学习目录:

提示:这里可以添加要学的内容
例如:
一、Python基础
1.列表推导式与条件赋值
2.匿名函数与map方法
3.zip对象与enumerate方法
二、numpy基础
1.Numpy数组的构造
2.Numpy数组的变形于合并
3.Numpy数组的切片于索引
4.常用函数
5.广播机制
6.向量与矢量的计算
三、练习
1.EX1: 利用列表推导式写矩阵乘法
2.EX2:更新矩阵
3.EX3:卡方统计量
4.EX4:改进矩阵计算性能
5.EX5:连续整数最大长度


学习时间:

提示:这里可以添加计划学习的时间
例如:
1.2020-12-14 22:40


笔记内容:

一、Python基础

1.列表推导式与条件赋值

列表推导式书写形式:  
**

[表达式 for 变量 in 列表] 或者 [表达式 for 变量 in 列表 if 条件]

**
这意味着 在先定义my_func 后

L = []
def my_func(x):
		return 2*x
for i in range(10):
		L.append(my_func(i))
print(L) 
#output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

等价于

[my_func(i) for i in range(10)]# 方括号很重要
 #output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  • 列表表达式还支持多层嵌套,如下面的例子中第一个 for 为外层循环,第二个为内层循环:
[m+'_'+n for m in ['a','b','c'] for n in ['1','2','3']]
#output:['a_1', 'a_2', 'a_3', 'b_1', 'b_2', 'b_3', 'c_1', 'c_2', 'c_3']

除了列表推导式,另一个实用的语法糖是带有 if 选择的条件赋值,其形式为 value = a if condition else b :

value = 'cat' if 2>1 else 'dog'
value
#output:‘cat’

等价于:

a,b = 'cat','dog'
condition = 2>1 #条件为true
if condition:
  value = 'cat'
else:
  value = 'dog'
value

截断列表中超过5的元素,即超过5的用5代替,小于5的保留原来的值:

L = [1, 2, 3, 4, 5, 6, 7]
[i if i <= 5 else 5 for i in L]
#output: [1, 2, 3, 4, 5, 5, 5]

2.匿名函数与map方法

匿名函数可以简单的吧上my_func改写成

my_func = lambda x:2*x
my_func(3)
#output : 6
multi_para_func = lambda a,b :a+b
multi_para_func(1,2)
#output : 3

但上面的用法其实违背了“匿名”的含义,事实上它往往在无需多处调用的场合进行使用,例如上面列表推导式中的例子,用户不关心函数的名字,只关心这种映射的关系:

[(lambda x:2*x)(i) for i in range(10)]#注意映射关系需要单独括号
#output:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

对于上述的这种列表推导式的匿名函数映射, Python 中提供了 map 函数来完成,它返回的是一个 map 对象,需要通过 list 转为列表:

list(map(lambda x:2*x,range(10)))
#output:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

对于多个输入值的函数映射,可以通过追加迭代对象实现:

list(map(lambda x,y:str(x)+"_"+y,range(10),list("abcde")))
#output:['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))
#output:[('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j')]
tuple(zip(L1, L2, L3))
#output: (('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j'))

往往会在循环迭代的时候使用到 zip 函数:

for i,d,j in zip(L1,L2,L3):
	print(i,d,j)
#output:
a d h
b e i
c f j

enumerate 是一种特殊的打包,它可以在迭代时绑定迭代元素的遍历序号:

L = list('abcd')
for index, value in enumerate(L):
		print(index, value)
#output:
0 a 
1 b
2 c
3 d

用 zip 对象也能够简单地实现这个功能:

for index, value in zip(range(len(L)), L):
		 print(index, value)
#output:
0 a
1 b
2 c
3 d

当需要对两个列表建立字典映射时,可以利用 zip 对象:

dict(zip(L1, L2))
#Output {'a': 'd', 'b': 'e', 'c': 'f'}

既然有了压缩函数,那么 Python 也提供了 * 操作符和 zip 联合使用来进行解压操作:

zipped = list(zip(L1, L2, L3))
zipped
#Output :[('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j')]
list(zip(*zipped)) # 三个元组分别对应原来的列表
#output:[('a', 'b', 'c'), ('d', 'e', 'f'), ('h', 'i', 'j')]

二、Numpy基础

1.Numpy数组的构造

最一般的方法是通过 array 来构造:

 import numpy as np #导入numpy
 np.array([1,2,3])
 #output:array([1, 2, 3])

下面讨论一些特殊数组的生成方式:

【a】等差序列: np.linspace, np.arange

np.linspace(1,5,11) # 起始、终止(包含)、样本个数
#Output:array([1. , 1.4, 1.8, 2.2, 2.6, 3. , 3.4, 3.8, 4.2, 4.6, 5. ])
np.arange(1,5,2) # 起始、终止(不包含)、步长
#Output: array([1, 3])

【b】特殊矩阵: zeros, eye, full

In [33]: np.zeros((2,3)) # 传入元组表示各维度大小,(行,列)
#Output: 
array([[0., 0., 0.],
       [0., 0., 0.]])
np.eye(3) # **3*3的单位矩阵**(以1为底)
#Output: 
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

np.eye(3, k=1) # 偏移主对角线1个单位的伪单位矩阵,k指向右移动多少个单位
#Output: 
array([[0., 1., 0.],
       [0., 0., 1.],
       [0., 0., 0.]])

 np.full((2,3), 10) # 元组传入大小,10表示填充数值,((x,y),z) x行y列,填入数值为10的
#Output: 
array([[10, 10, 10],
       [10, 10, 10]])

 np.full((2,3), [1,2,3]) # 通过传入列表填充每列的值
#Output: 
array([[1, 2, 3],
       [1, 2, 3]])

【c】随机矩阵: np.random

最常用的随机生成函数为 rand, randn, randint, choice ,它们分别表示0-1均匀分布的随机数组、标准正态的随机数组、随机整数组和随机列表抽样:

np.random.rand(3) # 生成服从0-1均匀分布的三个随机数
#Output: array([0.33475955, 0.95078732, 0.05285509])
np.random.rand(3, 3) # 注意这里传入的不是元组,每个维度大小分开输入
#Output: 
array([[0.1188322 , 0.51993935, 0.73054809],
       [0.97169376, 0.72724319, 0.84687781],
       [0.18001319, 0.8011098 , 0.05113275]])

对于服从区间 𝑎到 𝑏上的均匀分布可以如下生成:

a, b = 5, 15
(b - a) * np.random.rand(3) + a
#Output: array([ 9.67438882, 12.49445466,  6.51381903])

randn 生成了 𝑁(0,𝐈)的标准正态分布:

np.random.randn(3)
#Output: array([ 0.91321097, -0.02203455,  0.44235296])
np.random.randn(2, 2)
#Output: 
array([[ 0.49897634, -1.57842429],
       [-0.09213398,  0.00613158]])

In [43]:

对于服从方差为 𝜎2 均值为 𝜇

的一元正态分布可以如下生成:

sigma, mu = 2.5, 3
mu + np.random.randn(3) * sigma
#Output: array([5.89540275, 2.56563403, 1.56208693])

randint 可以指定生成随机整数的最小值最大值(不包含)和维度大小:

low, high, size = 5, 15, (2,2) # 生成5到14的随机整数
np.random.randint(low, high, size)
#Output: 
array([[ 7,  9],
       [13,  7]])

choice 可以从给定的列表中,以一定概率和方式抽取结果,当不指定概率时为均匀采样,默认抽取方式为有放回抽样:

my_list = ['a', 'b', 'c', 'd']
np.random.choice(my_list, 2, replace=False, p=[0.1, 0.7, 0.1 ,0.1])
#Output: array(['b', 'd'], dtype='<U1')
np.random.choice(my_list, (3,3))
#Output: 
array([['a', 'c', 'd'],
       ['d', 'b', 'c'],
       ['d', 'c', 'a']], dtype='<U1')

当返回的元素个数与原列表相同时,等价于使用 permutation 函数,即打散原列表:

np.random.permutation(my_list)
#Output: array(['d', 'c', 'a', 'b'], dtype='<U1')

最后,需要提到的是随机种子,它能够固定随机数的输出结果:

np.random.seed(0)
np.random.rand()
#Output: 0.5488135039273248
np.random.seed(0)
np.random.rand()
#Output: 0.5488135039273248

2.Numpy数组的变形于合并

【a】转置: T

np.zeros((2,3)).T
#Output: 
array([[0., 0.],
       [0., 0.],
       [0., 0.]])

【b】合并操作: r_, c_

对于二维数组而言, r_ 和 c_ 分别表示上下合并和左右合并:

np.r_[np.zeros((2,3)),np.zeros((2,3))]
#Output: 
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
np.c_[np.zeros((2,3)),np.zeros((2,3))]
#Output: 
array([[0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.]])

一维数组和二维数组进行合并时,应当把其视作列向量,在长度匹配的情况下只能够使用左右合并的 c_ 操作:

In [59]: try: …: np.r_[np.array([0,0]),np.zeros((2,1))]
…: except Exception as e: …: Err_Msg = e …:

In [60]: Err_Msg Out[60]: ValueError(‘all the input arrays must have
same number of dimensions, but the array at index 0 has 1 dimension(s)
and the array at index 1 has 2 dimension(s)’)

In [61]: np.r_[np.array([0,0]),np.zeros(2)] Out[61]: array([0., 0.,
0., 0.])

In [62]: np.c_[np.array([0,0]),np.zeros((2,3))] Out[62]: array([[0.,
0., 0., 0.],
[0., 0., 0., 0.]])

【c】维度变换: reshape

reshape 能够帮助用户把原数组按照新的维度重新排列。在使用时有两种模式,分别为 C 模式和 F 模式,分别以逐行和逐列的顺序进行填充读取。

target = np.arange(8).reshape(2,4)
target
#Output: 
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
target.reshape((4,2), order='C') # 按照行读取和填充
#Output: 
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
target.reshape((4,2), order='F') # 按照列读取和填充
#output
array([[0, 2],
       [4, 6],
       [1, 3],
       [5, 7]])

特别地,由于被调用数组的大小是确定的, reshape 允许有一个维度存在空缺,此时只需填充-1即可:

target.reshape((4,-1))
#Output: 
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])

下面将 n*1 大小的数组转为1维数组的操作是经常使用的:

target = np.ones((3,1))
target
#Output: 
array([[1.],
       [1.],
       [1.]])

target.reshape(-1)
#Output: array([1., 1., 1.])

3.Numpy数组的切片于索引

数组的切片模式支持使用 slice 类型的 start🔚step 切片,还可以直接传入列表指定某个维度的索引进行切片:

target = np.arange(9).reshape(3,3)
target
#Output: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
target[:-1, [0,2]]
#Output: 
array([[0, 2],
       [3, 5]])

此外,还可以利用 np.ix_ 在对应的维度上使用布尔索引,但此时不能使用 slice 切片:

target[np.ix_([True, False, True], [True, False, True])]
#Output: 
array([[0, 2],
       [6, 8]])

In [75]: target[np.ix_([1,2], [True, False, True])]
#Output: 
array([[3, 5],
       [6, 8]])

当数组维度为1维时,可以直接进行布尔索引,而无需 np.ix_ :

new = target.reshape(-1)
new[new%2==0]
#Output: array([0, 2, 4, 6, 8])

4.常用函数

【a】 where

where 是一种条件函数,可以指定满足条件与不满足条件位置对应的填充值:

a = np.array([-1,1,-1,0])
np.where(a>0, a, 5) # 对应位置为True时填充a对应元素,否则填充5
#Output: array([5, 1, 5, 5])

【b】 nonzero, argmax, argmin

这三个函数返回的都是索引, nonzero 返回非零数的索引, argmax, argmin 分别返回最大和最小数的索引:

a = np.array([-2,-5,0,1,3,-1])
np.nonzero(a)
#Output: (array([0, 1, 3, 4, 5], dtype=int64),)
a.argmax()
#Output: 4
a.argmin()
#Output: 1

【c】 any, all

any 指当序列至少 存在一个 True非零元素时返回 True ,否则返回 False

all 指当序列元素 全为 True 或非零元素时返回 True ,否则返回 False

a = np.array([0,1])
a.any()
#Output: True
a.all()
#Output: False

【d】 cumprod, cumsum, diff

cumprod, cumsum 分别表示累乘和累加函数,返回同长度的数组, diff 表示和前一个元素做差,由于第一个元素为缺失值,因此在默认参数情况下,返回长度是原数组减1

a = np.array([1,2,3])
a.cumprod()
#Output: array([1, 2, 6], dtype=int32)
a.cumsum()
#Output: array([1, 3, 6], dtype=int32)
np.diff(a)
#Output: array([1, 1])

【e】 统计函数

常用的统计函数包括 max, min, mean, median, std, var, sum, quantile ,其中分位数计算是全局方法,因此不能通过 array.quantile 的方法调用:

target = np.arange(5)
target
#Output: array([0, 1, 2, 3, 4])
target.max()
#Output: 4
np.quantile(target, 0.5) # 0.5分位数
#Output: 2.0

但是对于含有缺失值的数组,它们返回的结果也是缺失值,如果需要略过缺失值,必须使用 nan* 类型的函数,上述的几个统计函数都有对应的 nan* 函数。

target = np.array([1, 2, np.nan])
target
#Output: array([ 1.,  2., nan])
target.max()
#Output: nan
np.nanmax(target)
#Output: 2.0
np.nanquantile(target, 0.5)
#Output: 1.5

对于协方差和相关系数分别可以利用 cov, corrcoef 如下计算:

target1 = np.array([1,3,5,9])
target2 = np.array([1,5,3,-9])
np.cov(target1, target2)
#Output: 
array([[ 11.66666667, -16.66666667],
       [-16.66666667,  38.66666667]]) 

np.corrcoef(target1, target2)
#Output: 
array([[ 1.        , -0.78470603],
       [-0.78470603,  1.        ]])

最后,需要说明二维 Numpy 数组中统计函数的 axis 参数,它能够进行某一个维度下的统计特征计算,当 axis=0 时结果为列的统计指标,当 axis=1 时结果为行的统计指标:

target = np.arange(1,10).reshape(3,-1)
target
#Output: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
target.sum(0)
#Output: array([12, 15, 18])
target.sum(1)
#Output: array([ 6, 15, 24])

5.广播机制

广播机制用于处理两个不同维度数组之间的操作,这里只讨论不超过两维的数组广播机制。

【a】标量和数组的操作

当一个标量和数组进行运算时,标量会自动把大小扩充为数组大小,之后进行逐元素操作:

res = 3 * np.ones((2,2)) + 1
res
#Output: 
array([[4., 4.],
       [4., 4.]])

res = 1 / res
res
#Output: 
array([[0.25, 0.25],
       [0.25, 0.25]])

【b】二维数组之间的操作

当两个数组维度完全一致时,使用对应元素的操作,否则会报错,除非其中的某个数组的维度是 𝑚×1或者 1×𝑛 ,那么会扩充其具有 1 的维度为另一个数组对应维度的大小。例如, 1×2 数组和 3×2 数组做逐元素运算时会把第一个数组扩充为 3×2 ,扩充时的对应数值进行赋值。但是,需要注意的是,如果第一个数组的维度是 1×3 ,那么由于在第二维上的大小不匹配且不为 1,此时报错。

res = np.ones((3,2))
res
#Output: 
array([[1., 1.],
       [1., 1.],
       [1., 1.]])
res * np.array([[2,3]]) # 扩充第一维度为3
#Output: 
array([[2., 3.],
       [2., 3.],
       [2., 3.]])
res * np.array([[2],[3],[4]]) # 扩充第二维度为2
#Output: 
array([[2., 2.],
       [3., 3.],
       [4., 4.]])
res * np.array([[2]]) # 等价于两次扩充
#Output: 
array([[2., 2.],
       [2., 2.],
       [2., 2.]])

【c】一维数组与二维数组的操作

当一维数组 𝐴𝑘与二维数组 𝐵𝑚,𝑛 操作时,等价于把一维数组视作 𝐴1,𝑘 的二维数组,使用的广播法则与【b】中一致,当 𝑘!=𝑛 且 𝑘,𝑛 都不是 1时报错。

np.ones(3) + np.ones((2,3))
#Output: 
array([[2., 2., 2.],
       [2., 2., 2.]])
np.ones(3) + np.ones((2,1))
#Output: 
array([[2., 2., 2.],
       [2., 2., 2.]])
np.ones(1) + np.ones((2,3))
#Output: 
array([[2., 2., 2.],
       [2., 2., 2.]])

6.向量与矢量的计算

【a】向量内积: dot在这里插入图片描述

a = np.array([1,2,3])
b = np.array([1,3,5])
a.dot(b)
#Output: 22

在矩阵范数的计算中,最重要的是 ord 参数,可选值如下:
在这里插入图片描述

martix_target =  np.arange(4).reshape(-1,2)
martix_target
#Output: 
array([[0, 1],
       [2, 3]])

np.linalg.norm(martix_target, 'fro')
#Output: 3.7416573867739413

np.linalg.norm(martix_target, np.inf)
#Output: 5.0

np.linalg.norm(martix_target, 2)
#Output: 3.702459173643833
vector_target =  np.arange(4)
vector_target
#Output: array([0, 1, 2, 3])

np.linalg.norm(vector_target, np.inf)
#Output: 3.0

np.linalg.norm(vector_target, 2)
#Output: 3.7416573867739413

np.linalg.norm(vector_target, 3)
#Output: 3.3019272488946263

【c】矩阵乘法@:
在这里插入图片描述

a = np.arange(4).reshape(-1,2)
a
#Output: 
array([[0, 1],
       [2, 3]])

b = np.arange(-4,0).reshape(-1,2)
b
#Output: 
array([[-4, -3],
       [-2, -1]])

a@b
#Output: 
array([[ -2,  -1],
       [-14,  -9]])

三、练习

1.EX1: 利用列表推导式写矩阵乘法

一般的矩阵乘法根据公式,可以由三重循环写出:

In [138]: M1 = np.random.rand(2,3)

In [139]: M2 = np.random.rand(3,4)

In [140]: res = np.empty((M1.shape[0],M2.shape[1]))

In [141]: 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 …:

In [142]: ((M1@M2 - res) < 1e-15).all() # 排除数值误差 Out[142]: True
方法一:

M1 = np.random.rand(2,3)
M2 = np.random.rand(3,4)
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) < 1e-15).all() # 排除数值误差
#Output: True

方法二:

res = [[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])]
((M1@M2 - res) < 1e-15).all() 

2.EX2:更新矩阵

设矩阵 𝐴𝑚×𝑛 ,现在对 𝐴 中的每一个元素进行更新生成矩阵 𝐵 ,更新方法是 𝐵𝑖𝑗=𝐴𝑖𝑗∑𝑘=1𝑛1𝐴𝑖𝑘 ,例如下面的矩阵为 𝐴 ,则 𝐵2,2=5×(14+15+16)=3712 ,请利用 Numpy 高效实现。
在这里插入图片描述

A = np.arange(1,10).reshape(3,-1)
B = A*[ [sum(1/A[i][k] for k in range(A.shape[1])) ] for i in range(A.shape[0]) ]
B 
#output:
array([[1.83333333, 3.66666667, 5.5       ],
       [2.46666667, 3.08333333, 3.7       ],
       [2.65277778, 3.03174603, 3.41071429]])

3.EX3:卡方统计量

在这里插入图片描述

np.random.seed(0)
A = np.random.randint(10, 20, (8, 5))
A 
#output:
array([[15, 10, 13, 13, 17],
       [19, 13, 15, 12, 14],
       [17, 16, 18, 18, 11],
       [16, 17, 17, 18, 11],
       [15, 19, 18, 19, 14],
       [13, 10, 13, 15, 10],
       [12, 13, 18, 11, 13],
       [13, 13, 17, 10, 11]])
B = A.sum(0)*A.sum(1).reshape(-1, 1)/A.sum()
X = ((A-B)*(A-B)/B).sum()
X 
#output:
11.842696601945802

4.EX4:改进矩阵计算性能

在这里插入图片描述
在这里插入图片描述

(((B**2).sum(1).reshape(-1,1) + (U**2).sum(0) - 2*B@U)*Z).sum()
#output:100566

5.EX5:连续整数最大长度

输入一个整数的 Numpy 数组,返回其中递增连续整数子数组的最大长度。例如,输入 [1,2,5,6,7],[5,6,7]为具有最大长度的递增连续整数子数组,因此输出3;输入[3,2,1,2,3,4,6],[1,2,3,4]为具有最大长度的递增连续整数子数组,因此输出4。请充分利用 Numpy 的内置函数完成。(提示:考虑使用 nonzero, diff 函数)

def max_len(s):
    maxlen = 0
    l = 0
    for i in np.diff(s):
        if i == 1:
            l += 1
            if l > maxlen:
                maxlen = l
        else:
            l = 0
    return maxlen+1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值