pandas对缺失值的处理

# Pandas对缺失值的处理(判断是否为空、删除or丢弃、填充空值)

# pandas使用这些函数处理缺失值:
#     isnull 和 notnull :检验是否是空值,可用于series和df
#     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 
# 实例:特殊excel的读取、清洗、处理

# 步骤1 读取excel的时候,忽略前几个空行
studf = pd.read_excel("文件路径",skiprows=2)   #跳过前2个空行

# 步骤2 检测空值
studf.isnull()
studf["分数"].isnull()
studf["分数"].notnull()
# 筛选没有空分数的所有行
studf.loc[studf["分数"].notnull(),:]



# 步骤3: 删除掉全是空值的列
studf.dropna(axis = "columns",how="all",inplace = True)

# 步骤4 : 删除掉全是空值的行
studf.dropna(axis = "index",how = "all",inplace=True)


# 步骤5 : 将分数列为空的填充为0分
studf.fillna({"分数":0})
# 等同于
studf.loc[:,"分数"] = studf["分数"].fillna(0)


# 步骤6   将姓名的缺失值天填充
# 使用前面的有效值填充,有ffill:forword fill
studf.loc[:,"姓名"] = studf["姓名"].fillna(method = "ffill")

# 步骤7  将清洗好的excel保存
studf.to_excel("保存路径",index = False)   #去除索引
原文地址:https://www.cnblogs.com/spp666/p/11853418.html