Pandas之Dropna滤除缺失数据的实现方法
作者:yungeisme 时间:2022-03-30 03:29:42
约定:
import pandas as pd
import numpy as np
from numpy import nan as NaN
滤除缺失数据
pandas的设计目标之一就是使得处理缺失数据的任务更加轻松些。pandas使用NaN作为缺失数据的标记。
使用dropna使得滤除缺失数据更加得心应手。
一、处理Series对象
通过**dropna()**滤除缺失数据:
se1=pd.Series([4,NaN,8,NaN,5])
print(se1)
se1.dropna()
代码结果:
0 4.0
1 NaN
2 8.0
3 NaN
4 5.0
dtype: float640 4.0
2 8.0
4 5.0
dtype: float64
通过布尔序列也能滤除:
se1[se1.notnull()]
代码结果:
0 4.0
2 8.0
4 5.0
dtype: float64
二、处理DataFrame对象
处理DataFrame对象比较复杂,因为你可能需要丢弃所有的NaN或部分NaN。
df1=pd.DataFrame([[1,2,3],[NaN,NaN,2],[NaN,NaN,NaN],[8,8,NaN]])
df1
代码结果:
0 | 1 | 2 | |
---|---|---|---|
0 | 1.0 | 2.0 | 3.0 |
1 | NaN | NaN | 2.0 |
2 | NaN | NaN | NaN |
3 | 8.0 | 8.0 | NaN |
默认滤除所有包含NaN:
df1.dropna()
代码结果:
0 | 1 | 2 | |
---|---|---|---|
0 | 1.0 | 2.0 | 3.0 |
传入**how=‘all'**滤除全为NaN的行:
df1.dropna(how='all')
代码结果:
0 | 1 | 2 | |
---|---|---|---|
0 | 1.0 | 2.0 | 3.0 |
1 | NaN | NaN | 2.0 |
3 | 8.0 | 8.0 | NaN |
传入axis=1滤除列:
df1[3]=NaN
df1
代码结果:
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | 1.0 | 2.0 | 3.0 | NaN |
1 | NaN | NaN | 2.0 | NaN |
2 | NaN | NaN | NaN | NaN |
3 | 8.0 | 8.0 | NaN | NaN |
df1.dropna(axis=1,how="all")
代码结果:
传入thresh=n保留至少有n个非NaN数据的行:
df1.dropna(thresh=1)
df1.dropna(thresh=3)
代码结果:
0 | 1 | 2 | |
---|---|---|---|
0 | 1.0 | 2.0 | 3.0 |
1 | NaN | NaN | 2.0 |
2 | NaN | NaN | NaN |
3 | 8.0 | 8.0 | NaN |
来源:https://blog.csdn.net/weixin_38168620/article/details/79596798
标签:Pandas,Dropna,缺失数据
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python opencv缺陷检测的实现及问题解决
2023-03-10 20:41:55
![](https://img.aspxhome.com/file/2023/0/107880_0s.jpg)
如何理解PHP程序执行的过程原理
2023-10-08 14:45:10
细品Dreamweaver MX 内建FW技术
2008-06-04 09:41:00
Python设计模式中的状态模式你了解吗
2023-07-14 08:20:28
![](https://img.aspxhome.com/file/2023/2/60962_0s.png)
python中pass语句用法实例分析
2021-08-12 01:49:13
asp如何使用Office Chart 9.0 制作图表?
2010-06-05 12:41:00
python实现多线程暴力破解登陆路由器功能代码分享
2023-08-28 21:27:01
DSN和DSN-Less两种数据库连接方式哪一种更好?
2009-10-28 18:26:00
Python如何使用pymongo连接MongoDB数据库并进行相关操作
2023-05-12 01:21:49
![](https://img.aspxhome.com/file/2023/7/72017_0s.png)
laravel清除视图缓存的代码
2023-11-24 14:39:39
对Python3使运行暂停的方法详解
2021-02-05 22:55:21
![](https://img.aspxhome.com/file/2023/8/82738_0s.jpg)
详解OpenCV中直方图,掩膜和直方图均衡化的实现
2022-10-30 12:03:33
![](https://img.aspxhome.com/file/2023/8/107558_0s.jpg)
简单介绍一下pyinstaller打包以及安全性的实现
2021-07-23 15:34:56
![](https://img.aspxhome.com/file/2023/8/78718_0s.png)
Python利用PyExecJS库执行JS函数的案例分析
2022-10-26 08:53:19
![](https://img.aspxhome.com/file/2023/4/94154_0s.jpg)
python 使用tkinter与messagebox写界面和弹窗
2022-03-15 10:38:56
![](https://img.aspxhome.com/file/2023/2/70782_0s.png)
python 处理数字,把大于上限的数字置零实现方法
2022-11-13 09:20:56
[译稿]Web 字体的未来
2008-07-31 17:50:00
Css 清除浮动
2008-09-15 18:47:00
asp如何制作一个小巧的购物车?
2010-07-07 12:25:00
python jieba库的基本使用
2022-10-15 23:01:16