pandas学习笔记
前言
本文是pandas基础学习笔记,能帮助大家快速上手pandas。分别讲了以下几个方面,全文较长,建议收藏使用。
pandas数据结构及创建
索引Index
pandas统计分析
利用pandas进行SQL操作(增、删、改、查、聚合、排序、连接)
(1)pandas中的数据结构
DataFrame–DataFrame类似于numpy中的二维数组,同样可以通用numpy数组的函数和方法,而且还具有其他灵活应用
Series–Series类似于numpy中的一维数组,除了通吃一维数组可用的函数或方法,而且其可通过索引标签的方式获取数据,还具有索引的自动对齐功能
(2)数据结构的建立
Series
[1]通过一维数组创建序列
#导入pandas、numpy数据库
import numpy as np, pandas as pd
s2 = np.arange(10)
print(s2,type(s2))
s1 = pd.Series(s2)
print(s1)
[2]通过字典的方式创建序列
[3]通过DataFrame中的某一行或列创建序列
DataFrame
[1]通过二维数组创建数据框
##通过二维数组建立数据框
arr2 = np.array(np.arange(12)).reshape(4,3)
print(arr2,type(arr2))
df1 = pd.DataFrame(arr2)
print(df1)
print(type(df1))
[2]通过字典的方式创建数据框
#通过字典的方式创建数据框
dic2 = {'a':[1,2,3,4],'b':[5,6,7,8],'c':[9,10,11,12],'d':[13,14,15,16]}
print(dic2)
print(type(dic2))
df2 = pd.DataFrame(dic2)
print(df2)
print(type(df2))
#嵌套字典创建数据框
dic3 = {'one':{'a':1,'b':2,'c':3,'d':4},'two':{'a':5,'b':6,'c':7,'d':8},'three':{'a':9,'b':10,'c':11,'d':12}}
print(dic3)
print(type(dic3))
df3 = pd.DataFrame(dic3)
print(df3)
print(type(df3))
[3]通过数据框的方式创建数据框
#通过数据框的方式创建数据框\通过数据框的方式创建Series
df4 = df3[['one','three']]
print(df4)
print(type(df4))
s3 = df3['one']
print(s3)
print(type(s3))
索引Index
(1)索引的作用
-
通过索引获取目标数据
-
通过索引,使Series或DataFrame的操作实现自动化对齐
(2)代码实现
#获取数据
s4 = pd.Series(np.array([1,1,2,3,5,8]))
print(s4)
print(s4.index)#查看序列的索引
s4.index = ['a','b','c','d','e','f']##自定义索引
print(s4)
print('s4[3]: ',s4[3])
print('s4[e]: ',s4['e'])
##自动化对齐--两个序列进行算术运算
s5 = pd.Series(np.array([10,15,20,30,55,80]),index = ['a','b','c','d','e','f'])
print(s5)
s6 = pd.Series(np.array([12,11,13,15,14,16]),index = ['a','c','g','b','d','f'])
print(s6)
print(s5 + s6)
print(s5/s6)
对于数据框的对齐,不仅仅是行索引的自动对齐,同时也会自动对齐列索引(变量名)
数据框中同样有索引,而且数据框是二维数组的推广,所以其不仅有行索引,而且还存在列索引,关于数据框中的索引相比于序列的应用要强大的多.
利用pandas进行数据查询
功能:可以通过布尔索引有针对的选取原数据的子集、指定行、指定列
选取数据子集
student.head()
student.tail()
##loc查询指定的行
print(student.loc[[0,2,4,5,7]])#这里的loc索引标签函数必须是中括号[]
##查询指定的列--loc、列名
print(student[['Name','Height','Weight']].head())#如果多个列的话,必须使用双重中括号
print(student.loc[:,['Name','Height','Weight']].head())
print(student[(student['Sex']=='F') & (student['Age']>12)][['Name','Height','Weight']])#查询出所有12岁以上的女生姓名、身高和体重
print(student[(student['Sex']=='F') & (student['Age']>12)])#查询出所有12岁以上的女生信息
上面的查询逻辑其实非常的简单,需要注意的是,如果是多个条件的查询,必须在&(且)或者|(或)的两端条件用括号括起来。
利用DataFrames进行统计分析
(1)生成随机数
np.random.seed(1234)
d1 = pd.Series(2*np.random.normal(size = 100)+3)
d2 = np.random.f(2,4,size = 100)
d3 = np.random.randint(1,100,size = 100)
print('描述性统计指标: ', d1.describe()) #一次性输出多个描述性统计指标
(2)输出统计指标
必须注意的是,descirbe方法只能针对序列或数据框,一维数组是没有这个方法的
(3)同时对多列数据进行同样的操作(R语言中的apply函数)
##同时对多列数据进行同样的操作
df = pd.DataFrame(np.array([d1,d2,d3]).T,columns=['x1','x2','x3'])
print(df.head())
print(df.apply(stats))
(4)离散数据的统计描述–统计离散变量的观测数、唯一值个数、众数水平及个数–describe
print(student['Sex'].describe())
(5)连续变量的相关系数(corr)和协方差矩阵(cov)
print(df.corr())##连续型变量相关系数
print(df.corrwith(df['x1']))#corrwith--只关心其中一个变量与其他变量的相关系数
print(df.cov())##协方差矩阵
利用pandas实现SQL操作
(1)增(行、列)
##在SQL中常见的操作主要是增、删、改、查几个动作
dic = {'Name':['LiuShunxiang','Zhangshan'],'Sex':['M','F'],'Age':[27,23],'Height':[165.7,167.2],'Weight':[61,63]}
student2 = pd.DataFrame(dic)
print(student2)
###增--增加新行或新列
student3 = pd.concat([student,student2])#concat函数实现
print(student3)
#注意:在数据库中union必须要求两张表的列顺序一致,而这里concat函数可以自动对齐两个数据框的变量!
print(pd.DataFrame(student2, columns=['Age','Height','Name','Sex','Weight','Score']))##新增列
(2)删(删除表、观测行或变量列)
#删除表、观测行或变量列
del student2 #删除数据框student2, 通过del命令可以删除python的所有对象
print(student2)
print(student.drop([1,2,5,6]))##删除指定行
print(student.drop(['Height','Weight'],axis=1).head())#删除指定列
(3)改
#改--结合布尔索引和赋值的方法
例:将姓名为LiuShunxiang的同学身高修改为173
student3.loc[student3['Name'] == 'LiuShunxiang','Height']=173
print(student3[student3['Name'] == 'LiuShunxiang'][['Name','Height']])
(4)聚合
print(student.head())
print(student.groupby('Sex').mean())##根据性别分组,计算各组别中学生身高和体重的平均值--会默认对所有数值型数据进行聚合
print(student.drop('Age',axis=1).groupby('Sex').mean())##仅对身高、体重进行聚合--需要剔除年龄变量
print(student.groupby(['Sex','Age']).mean())#groupby还可以使用多个分组变量,例如根本年龄和性别分组,计算身高与体重的平均值
print(student.drop('Age',axis=1).groupby('Sex').agg([np.mean,np.median]))##对每个分组计算多个统计量
(5)排序
#排序---sort_index和sort_values实现序列和数据框的排序工作
Data = pd.Series(np.array(np.random.randint(1,20,10)))
print(Data)
print(Data.sort_index())
print(Data.sort_values(ascending=False))
print(student.sort_values(by = ['Age','Height']))#在数据框中按值排序
(6)多表连接
##连接--merge
dic2 = {'Name':['Alfred','Alice','Barbara','Carol','Henry','Jeffrey','Judy','Philip','Robert','Willam'],
'Score':[88,76,89,67,79,90,92,86,73,77]}
score = pd.DataFrame(dic2)
print(score)
stu_score1 = pd.merge(student, score, on='Name')##连接表student score
print(stu_score1)
#merge函数实现的是两个表之间的内连接,即返回两张表中共同部分的数据。可以通过how参数设置连接的方式,left为左连接;right为右连接;outer为外连接。
stu_score2 = pd.merge(student, score, on='Name', how='left')
print(stu_score2)
左连接实现的是保留student表中的所有信息,同时将score表的信息与之配对,能配多少配多少,对于没有配对上的Name,将会显示成绩为NaN。