Pandas缺失数据处理指南:检测、填充与删除

云舒
云舒
发布时间:2026-10-13| 6人浏览过
原创

本文详细介绍Pandas中处理缺失数据的完整流程。涵盖使用isnull和notnull检测NaN值,通过sum进行含NA的计算规则,利用fillna以标量或前后向填充缺失值,以及使用dropna删除含NA的行或列。

Pandas缺失数据处理概述

现实数据中缺失现象普遍存在,尤其在机器学习和数据挖掘领域,数据缺失会显著降低数据质量,进而严重影响模型预测的准确性。因此,对缺失值进行有效处理是提升模型精度与可靠性的关键环节。

通过重构索引(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 True g False 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

此处填充了零值;当然,也可以替换为任意其他指定的数值。

替换丢失(或)通用值

在实际应用中,常需将特定通用值替换为具体数值。这可以通过应用replace方法实现。使用标量值替换NA的效果与fillna()函数等效。

示例


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 1000 1 20 0 2 30 30 3 40 40 4 50 50 5 2000 60

one two 0 10 10 1 20 0 2 30 30 3 40 40 4 50 50 5 60 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]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。