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
import pandas as pd
- fpath='./datas/student_excel/student_excel.xlsx'
- df=pd.read_excel(fpath,skiprows=2)
- df

df.isnull()

以下两个函数输出的是相反的值:
df['分数'].isnull()、df['分数'].notnull()
- df['分数'].isnull()
- df['分数'].notnull()

筛选出没有空分数的所有行---df.loc[df['分数'].notnull(),:]
- #筛选出没有空分数的所有行
- df.loc[df['分数'].notnull(),:]

- df.dropna(axis='columns',how='all',inplace=True)
- df

- df.dropna(axis='index',how='all',inplace=True)
- df

df.fillna({'分数':0})

上述操作可以等于以下代码
- #上述操作可以等于一下代码
- df.loc[:,'分数']=df['分数'].fillna(0)
- df

使用前面的有效值填充,用ffill:forward fill
- df.loc[:,'姓名']=df['姓名'].fillna(method='ffill')
- df

df.to_excel('./datas/student_excel/student_excel_clean.xlsx',index=False)