Skip to Content
机器学习速查手册
book

机器学习速查手册

by Matt Harrison
July 2025
Intermediate to advanced
320 pages
3h 10m
Chinese
O'Reilly Media, Inc.
Content preview from 机器学习速查手册

第 5 章. 清理数据

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

我们可以使用 pandas 等通用工具和 pyjanitor 等专用工具来帮助清理数据。

列名

使用 pandas 时,使用 Python 友好的列名可以实现属性访问。pyjanitorclean_names 函数会返回一个列用小写、空格用下划线替换的 DataFrame:

>>> import janitor as jn
>>> Xbad = pd.DataFrame(
...     {
...         "A": [1, None, 3],
...         "  sales numbers ": [20.0, 30.0, None],
...     }
... )
>>> jn.clean_names(Xbad)
     a  _sales_numbers_
0  1.0             20.0
1  NaN             30.0
2  3.0              NaN
提示

我建议使用索引赋值、.assign 方法、.loc 或.iloc 赋值更新列。我还建议不要使用属性赋值来更新 pandas 中的列。由于存在覆盖与列同名的现有方法的风险,属性赋值不能保证有效。

pyjanitor 库很方便,但不允许我们删除列周围的空白。我们可以使用 pandas 对列重命名进行更精细的控制:

>>> def clean_col(name):
...     return (
...         name.strip().lower().replace(" ", "_")
...     )

>>> Xbad.rename(columns=clean_col)
     a  sales_numbers
0  1.0           20.0
1  NaN           30.0
2  3.0            NaN

替换缺失值

pyjanitor 中的coalesce 函数接收一个 DataFrame 和一个需要考虑的列列表。这与 Excel 和 SQL 数据库中的功能类似。它会返回每一行的第一个非空值:

>>> jn.coalesce(
...     Xbad,
...     columns=["A", "  sales numbers "],
...     new_column_name="val",
... )
    val
0   1.0
1  30.0
2   3.0

如果我们想用特定值填补缺失值,可以使用 DataFrame.fillna 方法:

>>> Xbad.fillna(10)
      A    sales numbers
0   1.0              20.0
1  10.0              30.0
2   3.0              10.0

或 pyjanitorfill_empty 函数:

>>> jn.fill_empty(
...     Xbad,
...     columns=["A", "  sales numbers "],
...     value=10,
... )
      A    sales numbers
0   1.0              20.0
1  10.0              30.0
2   3.0              10.0

通常,我们会在 pandas、scikit-learn 或 fancyimpute 中使用更细粒度的估算来执行每列的空替换。

在创建模型之前,您可以使用 pandas 来确保您已经处理了所有的缺失值,以此作为正确性检查。如果 DataFrame 中有任何单元格缺失,下面的代码会返回一个布尔值:

>>> df.isna().any().any()
True
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

雷达趋势观察:2025年7月

雷达趋势观察:2025年7月

Mike Loukides
R深度学习权威指南

R深度学习权威指南

Posts & Telecom Press, Joshua F. Wiley
Python高级编程(第2版)

Python高级编程(第2版)

Posts & Telecom Press, Michał Jaworski, Tarek Ziadé

Publisher Resources

ISBN: 9798341663046