数据预处理
- 数据分析的第一步是提高数据质量。数据清洗要做的就是处理缺失数据以及清除无意义的信息。这是数据价值链中最关键的步骤。垃圾数据,即使是通过最好的分析,也将产生错误的结果,并误导业务本身。
从现实世界中获取的数据往往是脏数据
有重复
有缺失
有异常 - 重复值处理
>>>import pandas as pd
>>>data=pd.DataFrame({'k1':['one']*3+['two']*4,'k2':[1,1,2,3,3,4,4]})
>>>data
k1 k2
0 one 1
1 one 1
2 one 2
3 two 3
4 two 3
5 two 4
6 two 4
>>>dup=data.duplicated() #检查重复值
>>>dup
0 False
1 True
2 False
3 False
4 True
5 False
6 True
dtype: bool
>>>data.drop_duplicates() #返回新数组,删除重复行
k1 k2
0 one 1
2 one 2
3 two 3
5 two 4
>>>data.drop_duplicates(['k1']) #删除k1列的重复数据
k1 k2
0 one 1
3 two 3
>>>data.drop_duplicates(['k1'],keep='last')
k1 k2
2 one 2
6 two 4
- 缺失值处理
对于缺失数据的处理方式有数据补齐、删除对应行、不处理等方法。
>>>import pandas as pd
>>>ranktable=pd.read_excel(r"d:\sjcltest.xlsx","Sheet1")
>>>print(ranktable)
No math physical Chinese
0 1 76.0 85 78.0
1 2 85.0 56 NaN
2 3 76.0 95 85.0
3 4 NaN 75 58.0
4 5 87.0 52 68.0
#检查缺失值
>>>print(ranktable.isnull().sum())
No 0
math 1
physical 0
Chinese 1
dtype: int64
>>>ranktable.dropna() #去除数据结构中值为空的数据行
No math physical Chinese
0 1 76.0 85 78.0
2 3 76.0 95 85.0
4 5 87.0 52 68.0
>>>ranktable['math'].fillna(0,inplace=True) #使用指定值填充缺失值
>>>print(ranktable)
No math physical Chinese
0 1 76.0 85 78.0
1 2 85.0 56 NaN
2 3 76.0 95 85.0
3 4 0.0 75 58.0
4 5 87.0 52 68.0
#格式:fillna(value=None,method=None,inplace=False)
#参数value用来指定要替换的值,可以是标量、字典、Series或DataFrame;
#参数inplace=True时表示原地替换,inplace=False时返回一个新的DataFrame对象而不对原来的DataFrame做任何修改。
>>>ranktable.fillna(method='pad') #用前一个数据值替换NaN
No math physical Chinese
0 1 76.0 85 78.0
1 2 85.0 56 78.0
2 3 76.0 95 85.0
3 4 0.0 75 58.0
4 5 87.0 52 68.0
>>>ranktable.fillna(method='bfill') #用后一个数据值替换NaN
No math physical Chinese
0 1 76.0 85 78.0
1 2 85.0 56 85.0
2 3 76.0 95 85.0
3 4 0.0 75 58.0
4 5 87.0 52 68.0
>>>ranktable.fillna(ranktable.mean()) #用平均数或者其他描述性统计量来代替NaN
No math physical Chinese
0 1 76.0 85 78.00
1 2 85.0 56 72.25
2 3 76.0 95 85.00
3 4 0.0 75 58.00
4 5 87.0 52 68.00
>>>ranktable.fillna({'math':0,'Chinese':50}) #传入一个字典,对不同的列填不同的值
No math physical Chinese
0 1 76.0 85 78.0
1 2 85.0 56 50.0
2 3 76.0 95 85.0
3 4 0.0 75 58.0
4 5 87.0 52 68.0
- 异常值处理
异常值,就是在数据集中不合理的值,又称离群点。- 某高校的本科生月平均消费1600元,但是有2个同学的月消费金额是700元和4000元,显然这两个同学的消费额明显不同于其他同学,这两个数值就被视为异常值。
- 某篮球运动员的身高达2.07米,这个特殊身高值在普通民众身高数据集中,就是异常值,但是它确实存在,并且是正确的,不能简单的做删除处理。
数据查询
访问位置 | 方法 | 备注 |
---|---|---|
访问列 | 变量名[列名] | 访问对应的列 |
访问行 | 变量名[n:m] | 访问n行到m-1行的数据 |
访问行和列 | 变量名.iloc[n1:n2,m1:m2] | 访问n1到(n2-1)行,m1到(m2-1)列的数据 |
访问位置 | 变量名.at[行名,列名] | 访问(行名,列名)位置的数据 |
>>>from pandas import DataFrame
>>>from pandas import Series
>>>df=DataFrame({'age':Series([26,29,24]),'name':Series(['Ken','Jerry','Ben'])})
>>>print(df['name']) #查看一列数据
0 Ken
1 Jerry
2 Ben
Name: name, dtype: object
>>>print(df[['name','age']]) #查看多列数据
name age
0 Ken 26
1 Jerry 29
2 Ben 24
C=df.iloc[0:1,0:2] #获取第0行到第1行(不含),与第0列到第2列(不含)交叉值 ;当使用位置索引时,区间左闭右开
>>>print(C)
age name
0 26 Ken
>>>D=df.at[0,'name'] #获取第0行与name列的交叉值
>>>print(D)
Ken
>>>df[df.age>25] #选择满足条件的数据
age name
0 26 Ken
1 29 Jerry
>>>df[df.age>30] #选择满足条件的数据
Empty DataFrame
Columns: [age, name]
Index: []
#格式:dataframe[condition]
#condition:过滤条件
#返回值:DataFrame
#常用的condition类型:比较运算:<、>、>=、<=、!= 如:df[df.comments>10000)];
#范围运算:between(left,right) 如:df[df.comments.between(1000,10000)];
#空置运算:如:df[df.title.isnull()];
#字符匹配:str.contains(patten,na=False)],如:df[df.title.str.contains('电台',na=False)]
#逻辑运算:&(与),|(或),not(取反);如:df[(df.comments>=1000)&(df.comments<=10000)]
>>>import pandas as pd
>>>df=pd.read_excel(r"d:\sjcltest.xlsx","Sheet1")
>>>df
No math physical Chinese ip
0 1 76.0 85 78.0 202.194.14.50
1 2 85.0 56 NaN 202.194.14.52
2 3 76.0 95 85.0 202.194.14.54
3 4 NaN 75 58.0 202.194.14.56
4 5 87.0 52 68.0 202.194.14.58
>>>df[df.math.isnull()] #空置判断
No math physical Chinese ip
3 4 NaN 75 58.0 202.194.14.56
>>>df[(df.math>=80)&(df.math<90)] #抽出满足某条件的行
No math physical Chinese ip
1 2 85.0 56 NaN 202.194.14.52
4 5 87.0 52 68.0 202.194.14.58
>>>df[(df.math>=80)&(df.math<90)][['No','math']] #抽出满足某条件的某些列的值
No math
1 2 85.0
4 5 87.0
>>>df[df.ip.str.contains('58',na=False)]
No math physical Chinese ip
4 5 87.0 52 68.0 202.194.14.58
数据修改
>>>from pandas import DataFrame
>>>from pandas import Series
>>>df=DataFrame({'age':Series([26,29,24]),'name':Series(['Ken','Jerry','Ben'])})
#根据行索引删除某行
>>>df.drop(1,axis=0) #axis=0表示行轴,也可以省略
age name
0 26 Ken
2 24 Ben
#df.drop(3,inplace=True) 原地删除
#根据列名进行删除某列
>>>df.drop('age',axis=1) #axis=1表示列轴,不可省略
name
0 Ken
1 Jerry
2 Ben
#第二种删除列的方法
#>>>del df['age']
#>>> df
# name
#0 Ken
#1 Jerry
#2 Ben
#末尾增加1列
>>>df['newColumn']=[2,4,8]
>>>df
name newColumn
0 Ken 2
1 Jerry 4
2 Ben 8
#末尾增加一行
>>>df.loc[len(df)]=[24,"KENKEN",7] #通过append方法传入字典结构数据
age name newColumn
0 26 Ken 2
1 29 Jerry 4
2 24 Ben 8
3 24 KENKEN 7
>>>df
age name newColumn
0 26 Ken 2
1 29 Jerry 4
2 24 Ben 8
3 24 KENKEN 7
>>>df.at[0,'age']=30 #修改指定行、列位置的数据值,直接对选择的数据赋值即可
>>>df
age name newColumn
0 30 Ken 2
1 29 Jerry 4
2 24 Ben 8
3 24 KENKEN 7
>>>import numpy as np
#修改某列的值
>>>df.loc[:,'newColumn']=np.random.randint((5,6,7,4)) #不是一个整体数组维度,加两个括号
>>>df
age name newColumn
0 30 Ken 2
1 29 Jerry 5
2 24 Ben 4
3 24 KENKEN 3
>>>df['newColumn']=df['newColumn']+10 #替换列数据
>>>df
age name newColumn
0 30 Ken 12
1 29 Jerry 15
2 24 Ben 14
3 24 KENKEN 13
>>>df.loc[df['age']==24,'newColumn']=100 #修改特定行的指定列
age name newColumn
0 30 Ken 12
1 29 Jerry 15
2 24 Ben 100
3 24 KENKEN 100
数据排序
>>>from pandas import DataFrame
>>>from pandas import Series
>>>df=DataFrame({'age':Series([30,29,24]),'name':Series(['Ken','Jerry','Ben']),'bj':Series([6,3,0])})
>>>df.sort_index(axis=0,ascending=False) #对行轴进行排序,降序
age name bj
2 24 Ben 0
1 29 Jerry 3
0 26 Ken 6
>>>df.sort_index(axis=0,ascending=True) #对行轴进行排序,升序
age name bj
0 26 Ken 6
1 29 Jerry 3
2 24 Ben 0
>>>import pandas as pd
>>>df=pd.read_excel(r"d:\sjcltest.xlsx","Sheet1")
>>>df.sort_values(by='math') #在指定列上对数据进行排序,默认升序
No math physical Chinese ip
0 1 76.0 85 78.0 202.194.14.50
2 3 76.0 95 85.0 202.194.14.54
1 2 85.0 56 NaN 202.194.14.52
4 5 87.0 52 68.0 202.194.14.58
3 4 NaN 75 58.0 202.194.14.56
>>>df.sort_values(by='math',ascending=False) #在指定列上对数据进行降序排序
No math physical Chinese ip
4 5 87.0 52 68.0 202.194.14.58
1 2 85.0 56 NaN 202.194.14.52
0 1 76.0 85 78.0 202.194.14.50
2 3 76.0 95 85.0 202.194.14.54
3 4 NaN 75 58.0 202.194.14.56
>>>df.sort_values(by=['math','physical'],ascending=False) #也可以使用by=['A','B']按多列进行排序,ascending=[False,True]
No math physical Chinese ip
4 5 87.0 52 68.0 202.194.14.58
1 2 85.0 56 NaN 202.194.14.52
2 3 76.0 95 85.0 202.194.14.54
0 1 76.0 85 78.0 202.194.14.50
3 4 NaN 75 58.0 202.194.14.56
数据合并
- 记录合并(两个表做并运算):是指两个结构相同的数据框合并成一个数据框。(也就是在一个数据框中追加另一个数据框的数据记录)
#格式:concat([dataFrame1,dataFrame2,...])
>>>import pandas as pd
>>>df=pd.read_excel(r"d:\sjcltest.xlsx","Sheet1")
>>>df1=df[df.math>=80]
>>>df2=df[df.math<80]
>>>df1
No math physical Chinese ip
1 2 85.0 56 NaN 202.194.14.52
4 5 87.0 52 68.0 202.194.14.58
>>> df2
No math physical Chinese ip
0 1 76.0 85 78.0 202.194.14.50
2 3 76.0 95 85.0 202.194.14.54
>>>df3=pd.concat([df1,df2])
>>>df3
No math physical Chinese ip
1 2 85.0 56 NaN 202.194.14.52
4 5 87.0 52 68.0 202.194.14.58
0 1 76.0 85 78.0 202.194.14.50
2 3 76.0 95 85.0 202.194.14.54
- 字段合并:是指将同一个数据框中的不同列进行合并,形成新的列。X=x1+x2+…
>>>import pandas as pd
>>>df=pd.read_excel(r"d:\sjcltest.xlsx","Sheet1")
>>>df.fillna(0,inplace=True)
>>>df
No math physical Chinese ip
0 1 76.0 85 78.0 202.194.14.50
1 2 85.0 56 0.0 202.194.14.52
2 3 76.0 95 85.0 202.194.14.54
3 4 0.0 75 58.0 202.194.14.56
4 5 87.0 52 68.0 202.194.14.58
>>>df['sum']=df['math']+df['physical']+df['Chinese']
>>>df
No math physical Chinese ip sum
0 1 76.0 85 78.0 202.194.14.50 239.0
1 2 85.0 56 0.0 202.194.14.52 141.0
2 3 76.0 95 85.0 202.194.14.54 256.0
3 4 0.0 75 58.0 202.194.14.56 133.0
4 5 87.0 52 68.0 202.194.14.58 207.0
- 字段匹配(两个表做连接):是指不同结构的数据框(两个或两个以上的数据框),按照一定的条件进行合并,即追加列。
merge(left,right,left_on,right_on,on,how)
#left:第一个数据框
#right:第二个数据框
#left_on:用来指定连接时依据的左侧第一个数据框的列名
#right_on:第二个数据框的用于匹配的列
#on:用来指定连接时依据的列名或包含若干列名的列表,要求指定的列名在两个DataFrame中都存在
#参数how的取值可以是'left','right','outer'或'inner'之一,表示数据连接的方式;
#返回值:DataFrame
>>>df1=pd.read_excel(r"d:\sjcltest.xlsx","Sheet4")
>>>df1
班级 班长
0 23080242 小龙
1 23080243 小华
2 23080244 小亮
3 23080245 小光
>>>df2=pd.read_excel(r"d:\sjcltest.xlsx","Sheet3")
>>>df2
学号 班级 姓名 性别 英语
0 2308024241 23080242 小龙 男 76
1 2308024244 23080242 小怡 女 66
2 2308024201 23080242 小培 男 60
3 2308024347 23080242 小华 女 67
>>>df3=pd.merge(df1,df2,left_on='班级',right_on='班级')
>>>pd.set_option('display.unicode.ambiguous_as_wide',True)
>>>pd.set_option('display.unicode.east_asian_width',True)
>>>df3[['学号','班级','姓名','班长']] #等值连接
学号 班级 姓名 班长
0 2308024241 23080242 小龙 小龙
1 2308024244 23080242 小怡 小龙
2 2308024201 23080242 小培 小龙
3 2308024347 23080242 小华 小龙
>>>df4=pd.merge(df1,df2,on='班级')
>>>df5=pd.merge(df1,df2)
>>>df4=pd.merge(df1,df2,on='班级',how='left')
>>>df4[['学号','班级','姓名','班长']] #左外连接
学号 班级 姓名 班长
0 2.308024e+09 23080242 小龙 小龙
1 2.308024e+09 23080242 小怡 小龙
2 2.308024e+09 23080242 小培 小龙
3 2.308024e+09 23080242 小华 小龙
4 NaN 23080243 NaN 小华
5 NaN 23080244 NaN 小亮
6 NaN 23080245 NaN 小光
知识点整理不易,如果对你有帮助,给个免费的赞支持一下吧!