数据丢失(缺失)在现实生活中总是一个问题。 机器学习和数据挖掘等领域由于数据缺失导致的数据质量差,在模型预测的准确性上面临着严重的问题。 在这些领域,缺失值处理是使模型更加准确和有效的重点。

使用重构索引(reindexing),创建了一个缺少值的DataFrame。 在输出中,NaN表示不是数字的值

一、检查缺失值

为了更容易地检测缺失值(以及跨越不同的数组dtype),Pandas提供了isnull()notnull()函数,它们也是Series和DataFrame对象的方法 

示例1

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('\n') print (df['one'].isnull())

输出结果:

        one       two     three
a 0.036297 -0.615260 -1.341327
b NaN NaN NaN
c -1.908168 -0.779304 0.212467
d NaN NaN NaN
e 0.527409 -2.432343 0.190436
f 1.428975 -0.364970 1.084148
g NaN NaN NaN
h 0.763328 -0.818729 0.240498 a False
b True
c False
d True
e False
f False
g True
h False
Name: one, dtype: bool

示例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'].notnull())
输出结果:
a     True
b False
c True
d False
e True
f True
g False
h True
Name: one, dtype: bool
 

二、缺少数据的计算

  • 在求和数据时,NA将被视为0
  • 如果数据全部是NA,那么结果将是NA

实例1

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('\n') print (df['one'].sum())

输出结果:

        one       two     three
a -1.191036 0.945107 -0.806292
b NaN NaN NaN
c 0.127794 -1.812588 -0.466076
d NaN NaN NaN
e 2.358568 0.559081 1.486490
f -0.242589 0.574916 -0.831853
g NaN NaN NaN
h -0.328030 1.815404 -1.706736 0.7247067964060545

示例2

import pandas as pd

df = pd.DataFrame(index=[0,1,2,3,4,5],columns=['one','two'])

print(df)
print('\n') print (df['one'].sum())

输出结果:

   one  two
0 NaN NaN
1 NaN NaN
2 NaN NaN
3 NaN NaN
4 NaN NaN
5 NaN NaN 0

三、填充缺少数据

Pandas提供了各种方法来清除缺失的值。fillna()函数可以通过几种方法用非空数据“填充”NA值。

用标量值替换NaN

以下程序显示如何用0替换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)
print('\n') print ("NaN replaced with '0':")
print (df.fillna(0))

输出结果:

        one       two     three
a -0.479425 -1.711840 -1.453384
b NaN NaN NaN
c -0.733606 -0.813315 0.476788
NaN replaced with '0':
one two three
a -0.479425 -1.711840 -1.453384
b 0.000000 0.000000 0.000000
c -0.733606 -0.813315 0.476788
 

在这里填充零值; 当然,也可以填写任何其他的值。

替换丢失(或)通用值

很多时候,必须用一些具体的值取代一个通用的值。可以通过应用替换方法来实现这一点。用标量值替换NAfillna()函数的等效行为。

示例

import pandas as pd

df = pd.DataFrame({'one':[10,20,30,40,50,2000],'two':[1000,0,30,40,50,60]})

print(df)
print('\n') print (df.replace({1000:10,2000:60}))

输出结果:

    one   two
0 10
1 20 0
2 30 30
3 40 40
4 50 50
5 60 one two
0 10
1 20 0
2 30 30
3 40 40
4 50 50
5 60

填写NA前进和后退

使用重构索引章节讨论的填充概念,来填补缺失的值。

方法 动作
pad/fill 填充方法向前
bfill/backfill 填充方法向后

示例1

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('\n') print (df.fillna(method='pad'))

输出结果:

        one       two     three
a -0.023243 1.671621 -1.687063
b NaN NaN NaN
c -0.933355 0.609602 -0.620189
d NaN NaN NaN
e 0.151455 -1.324563 -0.598897
f 0.605670 -0.924828 -1.050643
g NaN NaN NaN
h 0.892414 -0.137194 -1.101791 one two three
a -0.023243 1.671621 -1.687063
b -0.023243 1.671621 -1.687063
c -0.933355 0.609602 -0.620189
d -0.933355 0.609602 -0.620189
e 0.151455 -1.324563 -0.598897
f 0.605670 -0.924828 -1.050643
g 0.605670 -0.924828 -1.050643
h 0.892414 -0.137194 -1.101791
 

示例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.fillna(method='backfill'))

输出结果:

        one       two     three
a 2.278454 1.550483 -2.103731
b -0.779530 0.408493 1.247796
c -0.779530 0.408493 1.247796
d 0.262713 -1.073215 0.129808
e 0.262713 -1.073215 0.129808
f -0.600729 1.310515 -0.877586
g 0.395212 0.219146 -0.175024
h 0.395212 0.219146 -0.175024
 

四、丢失缺少的值

使用dropna函数和axis参数。 默认情况下,axis = 0,即在行上应用,这意味着如果行内的任何值是NA,那么整个行被排除。

实例1

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.dropna())
输出结果 :
        one       two     three
a -0.719623 0.028103 -1.093178
c 0.040312 1.729596 0.451805
e -1.029418 1.920933 1.289485
f 1.217967 1.368064 0.527406
h 0.667855 0.147989 -1.035978
 

示例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.dropna(axis=1))
输出结果:
Empty DataFrame
Columns: []
Index: [a, b, c, d, e, f, g, h]
 

Pandas | 17 缺失数据处理的更多相关文章

  1. Pandas缺失数据处理

    Pandas缺失数据处理 Pandas用np.nan代表缺失数据 reindex() 可以修改 索引,会返回一个数据的副本: df1 = df.reindex(index=dates[0:4], co ...

  2. 第十二节:pandas缺失数据处理

    1.isnull():检查是否含有确实数据 2.fillna():填充缺失数据 3.dropna() :删除缺失值 4.replace():替换值

  3. 数据分析之pandas常见的数据处理(四)

    常见聚合方法 方法 说明 count 计数 describe 给出各列的常用统计量 min,max 最大最小值 argmin,argmax 最大最小值的索引位置(整数) idxmin,idxmax 最 ...

  4. Pandas 拼接操作 数据处理

    数据分析 生成器 迭代器 装饰器 (两层传参) 单例模式() ios七层 io多路 数据分析:是把隐藏在一些看似杂乱无章的数据背后的信息提炼出来,总结出所研究对象的内在规律 pandas的拼接操作 p ...

  5. pandas删除缺失数据(pd.dropna()方法)

    1.创建带有缺失值的数据库:   import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), ind ...

  6. Pandas基础用法-数据处理【全】-转

    完整资料:[数据挖掘入门介绍] (https://github.com/YouChouNoBB/data-mining-introduction) # coding=utf-8 # @author: ...

  7. 05-pandas索引切片读取数据缺失数据处理

    引入 numpy已经能够帮助我们处理数据,能够结合matplotlib解决我们数据分析的问题,那么pandas学习的目的在什么地方呢? numpy能够帮我们处理处理数值型数据,但是这还不够 很多时候, ...

  8. Pandas和常见数据处理小模块

    文章目录 前言 Pandas部分 根据某一列找另一列 根据条件变换每一列 按照标签保存为DataFrame 数据处理 切分数据集和测试集 其他 计时 前言 pandas 确实很好用, 但是网上的教程参 ...

  9. python pandas模块,nba数据处理(1)

    pandas提供了使我们能够快速便捷地处理结构化数据的大量数据结构和函数.pandas兼具Numpy高性能的数组计算功能以及电子表格和关系型数据(如SQL)灵活的数据处理能力.它提供了复杂精细的索引功 ...

随机推荐

  1. Spring boot 梳理 - @SpringBootConfiguration

    @SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类, 并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到sprin ...

  2. 部份css样式详解(附实际应用)

    本文的所有实例均基于博客园的页面定制. 所有表格内容来自W3CSchool. 页面背景(background) 博客开通之后,很多人最先做的事情一定是改页面的背景,换成一张图片或者换上一个自己喜欢的颜 ...

  3. vs code编码设置

    在使用vs code(版本1.35.0)打开文件时,出现乱码问题,可通过如下方式设置: 1.针对单个文件 点击右下角的编码按钮(图中为UTF-8),然后选择操作,通过编码重新打开(Reopen wit ...

  4. Angular 页面初始化动画

    用于进入组件前的加载动画 第一步:index.html 定义动画模板和样式 // 样式 <style type="text/css">.preloader { posi ...

  5. 使用gtest(googletest)进行c++单元测试

    这是系列文章的第三篇,前两篇https://www.cnblogs.com/gaopang/p/11243367.html和https://www.cnblogs.com/gaopang/p/1158 ...

  6. springcloud -- sleuth+zipkin整合rabbitMQ详解

    为什么使用RabbitMQ? 我们已经知道,zipkin的原理是服务之间的调用关系会通过HTTP方式上报到zipkin-server端,然后我们再通过zipkin-ui去调用查看追踪服务之间的调用链路 ...

  7. 教你制作挂件头像 | 小程序七十二变之 canvas 绘制国旗头像

    昨天朋友圈被「请给我一面国旗@微信官方」刷屏,虽然知道是假的,但是从另一个角度来看,弄清楚如何实现更有趣. 1.canvas 这就不得不提到小程序中的 API canvas,H5 中也是有 canva ...

  8. MyBatis resultType用Map 返回值中有NULL则缺少字段 返回值全NULL则map为null

    这个问题我大概花了2个小时才找到结果 总共需要2个设置 这里是对应springboot中的配置写法 @select("select sum(a) a,sum(b) b from XXX wh ...

  9. Windows中0环与3环通信(常规方式)

    Windows内核分析索引目录:https://www.cnblogs.com/onetrainee/p/11675224.html 一.知识点讲解 1. 设备对象 我们在开发窗口程序的时候,消息被封 ...

  10. Ubuntu安装Chrome浏览器及解决启动no-sandbox问题

    1.安装浏览器 # apt-get install gonme # apt-get update # apt-get install google-chrome-stable 2.启动Chrome浏览 ...