1、快速浏览数据集
#导入数据
import pandas as pd
df=pd.read_excel("/Users/tinawang/Documents/python/case.xlsx",sheet_name="清洗")
df
id price name
0 1 999999.0 豆角炒肉
1 2 10.0 米线
2 2 10.0 米线
3 3 NaN 西红柿鸡蛋盖饭
4 4 50.0 红烧鱼
5 5 45.0 排骨汤
6 6 5.0 土豆丝
#输出数据详情信息,可知price列有一个空值
print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7 entries, 0 to 6
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 7 non-null int64
1 price 6 non-null float64
2 name 7 non-null object
dtypes: float64(1), int64(1), object(1)
memory usage: 296.0+ bytes
#获取前5行数据
print(df.head())
id price name
0 1 999999.0 豆角炒肉
1 2 10.0 米线
2 2 10.0 米线
3 3 NaN 西红柿鸡蛋盖饭
4 4 50.0 红烧鱼
#获取前1行数据
print(df.head(1))
id price name
0 1 999999.0 豆角炒肉
2、数据清洗:缺失值&异常值&重复值
知识点汇总
判断是否为空 | df['字段名'].isnull() |
判断是否重复 | df['字段名'].duplicated() |
删除 | df.drop(index=df[df['字段名'].isnull()].index,inplace=True) df.drop(index=df[df['字段名'].duplicated()].index,inplace=True) |
补充 | df['字段名'].fillna(填充值,inplace=True) |
2.1、缺失值处理
#判断每行数据是否为null
print(df["price"].isnull())
#输出
0 False
1 False
2 False
3 True
4 False
5 False
6 False
Name: price, dtype: bool
#选中缺失所在行组成新的数据框
dfpriceNull=df[df["price"].isnull()]
print(dfpriceNull)
#输出
id price name
3 3 NaN 西红柿鸡蛋盖饭
#删除缺失值所在行:drop
dfpriceNull=df[df["price"].isnull()]#先判断缺失值所在的行索引
df.drop(index=dfpriceNull.index,inplace=True)#根据缺失值所在行的行索引删除该行
print(df)
id price name
0 1 999999.0 豆角炒肉
1 2 10.0 米线
2 2 10.0 米线
4 4 50.0 红烧鱼
5 5 45.0 排骨汤
6 6 5.0 土豆丝
#用默认值填充缺失值
#用固定默认值0.1替代空值
df["price"].fillna(0.1,inplace=True)
print(df)
id price name
0 1 999999.0 豆角炒肉
1 2 10.0 米线
2 2 10.0 米线
3 3 0.1 西红柿鸡蛋盖饭
4 4 50.0 红烧鱼
5 5 45.0 排骨汤
6 6 5.0 土豆丝
#用全部非空值的均值替代空值
df["price"].fillna(df['price'].mean(),inplace=True)
print(df)
id price name
0 1 999999.0 豆角炒肉
1 2 10.0 米线
2 2 10.0 米线
3 3 166686.5 西红柿鸡蛋盖饭
4 4 50.0 红烧鱼
5 5 45.0 排骨汤
6 6 5.0 土豆丝
2.2、异常值
#判断是否存在异常值
import pandas as pd
df=pd.read_excel("/Users/tinawang/Documents/python/case.xlsx",sheet_name="清洗")
df
#判断price列是否有如下异常值[999999,1999999,299999]
df["price"].isin([999999,1999999,299999])#是否存在
Out[498]:
0 True
1 False
2 False
3 False
4 False
5 False
6 False
~df["price"].isin([999999,1999999,299999])#是否不存在
0 False
1 True
2 True
3 True
4 True
5 True
6 True
#删除异常值
dfWrongPrice=df[df["price"].isin([999999,1999999,299999])]
df.drop(index=dfWrongPrice.index,inplace=True)
df
id price name
1 2 10.0 米线
2 2 10.0 米线
3 3 NaN 西红柿鸡蛋盖饭
4 4 50.0 红烧鱼
5 5 45.0 排骨汤
6 6 5.0 土豆丝
2.3、重复值
import pandas as pd
df=pd.read_excel("/Users/tinawang/Documents/python/case.xlsx",sheet_name="清洗")
df
print(df["id"].duplicated())#当一个值第二次出现的时候,就会是True,第一条是Fasle
0 False
1 False
2 True
3 False
4 False
5 False
6 False
dfrepeat=df[df["id"].duplicated()]
print(dfrepeat)
id price name
2 2 10.0 米线
df.drop(index=dfrepeat.index,inplace=True)
print(df)
id price name
0 1 999999.0 豆角炒肉
1 2 10.0 米线
3 3 NaN 西红柿鸡蛋盖饭
4 4 50.0 红烧鱼
5 5 45.0 排骨汤
6 6 5.0 土豆丝