一、处理缺失值的四个函数
- ①isnull函数:检测是否是空值,可用于df和series
- ②notnull函数:检测是否是空值,可用于df和series
- ③dropna函数:丢弃、删除缺失值
参数 | 介绍 |
---|---|
axis | 删除行还是列,{0 or ‘index’, 1 or ‘columns’}, default 0 |
how | 如果等于any则任何值为空都删除,如果等于all则所有值都为空才删除 |
inplace | 如果为True则修改当前df,否则返回新的df |
- ④fillna函数:填充空值
参数 | 介绍 |
---|---|
value | 用于填充的值,可以是单个值,或者字典(key是列名,value是值) |
method | 等于ffill使用前一个不为空的值填充forword fill;等于bfill使用后一个不为空的值填充backword fill |
axis | 按行还是列填充,{0 or ‘index’, 1 or ‘columns’} |
inplace | 如果为True则修改当前df,否则返回新的df |
二、使用
1.1 数据样子
未处理前
要清洗后的样式
1.2 处理
①读取表格,跳过两行
import pandas as pd
df = pd.read_excel('./student.xlsx', skiprows=2)
print(df.head())
②检测缺失值
print(df.isnull())
# print(df.notnull())
③删除全是空值的列
# axis可以写1,how将全部为空,inplace是本表应用
df.dropna(axis='columns', how='all', inplace=True)
print(df)
④删除全是空值得行
# axis可以写0,how将全部为空,inplace是本表应用
df.dropna(axis='index', how='all', inplace=True)
print(df)
⑤将分数列为空的填充为0
# df.fillna({'分数':0})#效果同下
df.loc[:, '分数'] = df['分数'].fillna(0)
print(df)
⑥将姓名的缺失值填充
df.loc[:, '姓名'] = df['姓名'].fillna(method="ffill")#按照上一行自动填充
print(df)
⑦将清洗的表格保存
df.to_excel("./new_student.xlsx", index=False)