Pandas系列教程(6)Pandas缺失值处理

Pandas缺失值处理

Pandas使用这些函数处理缺失值:

  • isnull和notnull: 检测是否是空值,可用于df和Series

  • dropna: 丢弃,删除缺失值

    • axis: 删除行还是列,{0 ro '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 ro 'index', 1 or 'columns'}

    • inplace: 如果为True则修改当前df, 否则返回新的df

实例:特殊Excel的读取,清洗,处理

import pandas as pd

# 第一步:读取Excel的时候忽略前几个空行
print('*' * 25, '第一步:读取Excel的时候忽略前几个空行', '*' * 25)
file_path = "../datas/student_excel/student_excel.xlsx"
studf = pd.read_excel(file_path, skiprows=2)
print(studf)

# 第二步:检测空值
print('*' * 25, '第二步:检测空值', '*' * 25)
print(studf.isnull())
print('*' * 25, '筛选分数为空的值', '*' * 25)
print(studf['分数'].isnull())
print('*' * 25, '筛选分数不为空的值', '*' * 25)
print(studf['分数'].notnull())
print('*' * 25, '筛选没有空分数的所有行', '*' * 25)
print(studf.loc[studf['分数'].notnull(), :])

# 第三步:删除全是空值的列
studf.dropna(axis='columns', how='all', inplace=True)
print('*' * 25, '第三步:删除全是空值的列', '*' * 25)
print(studf)

# 第四步:删除全是空值的行
studf.dropna(axis='index', how='all', inplace=True)
print('*' * 25, '第四步:删除全是空值的行', '*' * 25)
print(studf)

# 第五步:将分数列为空的填充为0分
# studf.fillna({"分数": 0})   # 有点小问题
studf.loc[:, '分数'] = studf['分数'].fillna(0)  # 两种方式相同
print('*' * 25, '第五步:将分数列为空的填充为0分', '*' * 25)
print(studf)

# 第六步:将姓名的缺失值填充
studf.loc[:, '姓名'] = studf['姓名'].fillna(method='ffill')
print('*' * 25, '第六步:将姓名的缺失值填充', '*' * 25)
print(studf)

# 第七步:将清洗好的execel保存
print('*' * 25, '第七步:将清洗好的execel保存', '*' * 25)
studf.to_excel("../datas/student_excel/student_excel_clean.xlsx", index=False)

 

原文地址:https://www.cnblogs.com/xingxingnbsp/p/13851826.html