Pandas缺失值处理

一、什么是稀疏数据?

       稀疏数据指的是在数据库或者数据集中存在大量缺失数据或者空值,我们把这样的数据集称为稀疏数据集。
大致原因

  • 由于调查不当产生的稀疏数据;
  • 由于天然限制产生的稀疏数据;
  • 文本挖掘中产生的稀疏数据。

      缺失值在统计分析中经常被用到,在R语言中,is.na()、is.nan()和is.infinite()可分别用来识别缺失值、不可能值和无穷值。在python中空值为None, 在java中空值为null,但是到pandas中空值被显示为NaN。pandas中我们经常处理是:判断是否是缺失值、直接删除缺失值、填充缺失值。

常用函数

  • df.isnull()、df.notnull():两个函数互为取反
  • df.isna():等同于df.isnull()
  • df.dropna():删除缺失值
  • df.fillna():填充缺失值

二、缺失值处理

1、检查缺失值

为了检测缺失值,Pandas 提供了 isnull() 和 notnull() 两个函数,适用于 Series 和 DataFrame 对象。

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'])
df = df.reindex(['d', 'e', 'f')
print(df['noe'].isnull())

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'])
df = df.reindex(['d', 'e', 'f'])
print(df['one'].notnull())

 2、缺失数据计算

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f','h'],
            columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print (df['one'].sum())

 3、清理并填充缺失值

fillna() 函数可以实现用非空数据“填充”NaN 值。

1) 用标量值替换NaN值

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'],
            columns=['one','two', 'three'])
df = df.reindex(['a', 'b', 'c'])
print(df)
#用 0 填充 NaN
print (df.fillna(0))

 2) 向前和向后填充NA

 ffill() 向前填充和 bfill() 向后填充,使用这两个函数也可以处理 NA 值

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f','h'],
        columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print df.fillna(method='ffill')

3) 使用replace替换通用值 

import pandas as pd
import numpy as np
df = pd.DataFrame({'one':[10,20,30,40,50,666], 'two':[99,0,30,40,50,60]})
#使用replace()方法
print (df.replace({99:10,666:60,0:20}))

 4) 删除缺失值

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f','h'],
                columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print(df)
#删除缺失值
print (df.dropna())

 三、参考

Pandas数据分析—对缺失值的处理_Wumbuk的博客-CSDN博客_pandas处理缺失值 

如何用pandas处理缺失值_zoujiahui_2018的博客-CSDN博客_pandas缺失值处理 

图解pandas的缺失值处理 - 知乎
 

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

**星光*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值