pandas有三类函数可以处理缺失值:
isnull和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;
下面我们上一个例子,假如我有一份这样的数据

这样的数据我们拿到之后就需要做数据清洗才能做进一步的数据分析,我们先用vscode来读取它
import pandas as pd
pd.set_option('display.unicode.ambiguous_as_wide', True) #处理数据的列标题与数据无法对齐的情况
pd.set_option('display.unicode.east_asian_width', True) #无法对齐主要是因为列标题是中文
result=pd.read_excel(r'data\20211031.xls',encoding='gbk',skiprows=2) #skiprows=2 意思是跳过2行读取
print(result)

我们读取文档后发现有很多空值,所以我们就要对这些空值进行处理
首先,检测空值
student=pd.read_excel(r'data\20211031.xls',encoding='gbk',skiprows=2) #skiprows=2 意思是跳过2行读取
print(student.isnull())

我们可以看到第一列和第二列全是空,还有一些行也为空
当然我们也可以用单个列去做判断
student=pd.read_excel(r'data\20211031.xls',encoding='gbk',skiprows=2) #skiprows=2 意思是跳过2行读取
print(student['姓名'].isnull()) #检测为空
print(student['姓名'].notnull()) #检测不为空

接下来我们筛选出没有空分数的所有行(筛选出所有分数不为空的所有行)
student=pd.read_excel(r'data\20211031.xls',encoding='gbk',skiprows=2) #skiprows=2 意思是跳过2行读取
fraction=student.loc[student['分数'].notnull(),:]
print(fraction)

然后删除全部为空值的列
student=pd.read_excel(r'data\20211031.xls',encoding='gbk',skiprows=2) #skiprows=2 意思是跳过2行读取
student.dropna(axis=1,how='all',inplace=True)
print(student)

输出结果之后,我们还是看到有很多空值的行,接下来我们就删掉所有空值的行
student=pd.read_excel(r'data\20211031.xls',encoding='gbk',skiprows=2) #skiprows=2 意思是跳过2行读取
student.dropna(axis=1,how='all',inplace=True)
student.dropna(axis=0,how='all',inplace=True)
print(student)

完成之后我们还看到有空值,姓名的列下有空值,分数的列下也有空值,我们先处理分数列,把小明数学的分数改成0
student.loc[:,'分数']=student.fillna(0)
print(student)

接下来就需要把姓名的缺失值进行填充
student.loc[:,'分数']=student.fillna(0)
student.loc[:,'姓名']=student.fillna(method='ffill')
print(student)

最后把清洗好的数据保存
student.to_excel(r'data\20211031_clean.xls',index=False) #这个index=False的意思是把数据前面第一列的序列号去掉
