zoukankan      html  css  js  c++  java
  • 数据分析之处理丢失数据

    处理丢失数据:

      有两种丢失数据

        None

        np.nan(NaN的形式)

    1 None

      None是Python自带的,其类型为python object。因此,None不能参与到任何计算中。  

    import numpy as np
    import pandas as pd
    from pandas import Series,DataFrame
    type(None)
    #NoneType
    type(np.nan)
    #float
    np.nan 的数据类型可以进行数据运算
    np.nan + 1 得到的数据类型还是np.nan np.nan是浮点类型,能参与到计算中。但计算的结果总是NaN。
    2 pandas中的None与NaN

    pandas中的None与NaN

      1 pandas中的None与np.nan是视作np.nan

      创建DataFrame 

    df = DataFrame(data=np.random.randint(0,100,size=(13,9)))
    df.iloc[2,4] = None
    df.iloc[5,5] = np.nan
    df.iloc[2,2] = None
    df.iloc[7,3] = None
    df.iloc[6,8] = None

     

    2 pandas处理空值操作

    isnull() 判断数据是否为空,空是True
    notnull() 判断数据是否为空,空是False
    dropna(): 过滤丢失数据,一般不用,有可能误删数据,
    fillna(): 填充丢失数据
    df.isnull().any(axis=1) 判断行有空值吗 有空值是True
    df.notnull().all(axis=1) 判断行有空值吗 有空值是False
    
    一般是这样组合使用的
    df.loc[df.notnull().all(axis=1)]取出空值的行
    df.dropna(axis=0) 删除行中有空值的行,0是行

     3 填充函数 Series/DataFrame的数据

    df.fillna(method='ffill',axis=0)  ffill 将空值添上上一行元素的数据
    
    df.fillna(method='bfill',axis=0)  ffill 将空值添上下一行元素的数据

    数据清洗的案例:

    文件下载:

    https://pan.baidu.com/s/1FFJsgnB1wTW83uJQTJgZew、

    #方式一 删除空值的行
    temp_df = pd.read_excel('测试数据.xlsx') temp_df = temp_df[[1,2,3,4]] #取出数据的前四列 temp_df.dropna(axis=0) 将空值的行删除

    # 方式二 填充空值的行
    #首次填充之后对应的结果 test_df = temp_df.fillna(method='bfill',axis=0) #校验test_df中还是否存在空值:查看列中是否还有空值 test_df.isnull().any(axis=0)
  • 相关阅读:
    关于计算机改名无法连接TFS的问题
    配置 SQL Server 2008 Email 发送以及 Job 的 Notification通知功能
    javascript原型链中 this 的指向
    JavaScript中的构造函数 renturn
    Javascript中valueOf与toString区别
    JavaScript 中this与Dom中的注意
    SQL优化 CREATE STATISTICS
    Maven根据不同的环境打包不同的配置
    Maven build标签
    解决Maven报Plugin execution not covered by lifecycle configuration问题
  • 原文地址:https://www.cnblogs.com/lulin9501/p/11347698.html
Copyright © 2011-2022 走看看