百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

python数据清洗的三个常用的处理方式!

off999 2024-09-16 00:48 26 浏览 0 评论

关于python数据处理过程中三个主要的数据清洗说明,分别是缺失值/空格/重复值的数据清洗。

这里还是使用pandas来获取excel或者csv的数据源来进行数据处理。若是没有pandas的非标准库需要使用pip的方式安装一下。

pip install pandas

准备一下需要处理的脏数据,这里选用的是excel数据,也可以选择其他的格式数据,下面是源数据截图。

使用pandas的read_excel()函数读取出我们需要处理的data.xlsx文件。

# Importing the pandas library and giving it an alias of pd.
import pandas as pd

# Reading the excel file and storing it in a variable called `result_`
result_ = pd.read_excel('D:/test/data.xlsx')

# Printing the dataframe.
print(result_)

注意,若是新的python环境直接安装pandas模块后执行上面的读取excel数据代码可能会出现没有openpyxl模块的情况。

这时候,我们使用pip的方式再次安装一下openpyxl即可。

pip install openpyxl

完成后再次执行读取excel数据的代码块会成功的返回结果。

#           姓名    年龄    班级   成绩 表现
# 0   Python 集中营  10  1210   99  A
# 1   Python 集中营  11  1211  100  A
# 2   Python 集中营  12  1212  101  A
# 3   Python 集中营  13  1213  102  A
# 4   Python 集中营  14  1214  103  A
# 5   Python 集中营  15  1215  104  A
# 6   Python 集中营  16  1216  105  A
# 7   Python 集中营  17  1217  106  A
# 8   Python 集中营  18  1218  107  A
# 9   Python 集中营  19  1219  108  A
# 10  Python 集中营  20  1220  109  A
# 11  Python 集中营  21  1221  110  A
# 12  Python 集中营  22  1222  111  A
# 13  Python 集中营  23  1223  112  A
# 14  Python 集中营  24  1224  113  A
# 15  Python 集中营  25  1225  114  A
# 16  Python 集中营  26  1226  115  A
# 17  Python 集中营  27  1227  116  A
# 18  Python 集中营  28  1228  117  A
#
# Process finished with exit code 0

准备好数据源之后,我们使用三个方式来完成对源数据的数据清洗。

1. strip函数清除空格

首先,将所有的列名称提取出来,使用DataFrame对象的columns函数进行提取。

# Extracting the column names from the dataframe and storing it in a variable called `columns_`.
columns_ = result_.columns.values

# Printing the column names of the dataframe.
print(columns_)

# ['  姓名  ' '年龄' '班级' '成绩' '表现']

从列名称的打印结果发现'姓名'这一列是存在空格的,我们直接查找列名称是找不到的,因为需要对列名称的空格进行数据清洗。

为了减少代码块的使用,我们这里直接使用列表推导式的方式对列名称的空格进行清洗。

# A list comprehension that is iterating over the `columns_` list and stripping the whitespaces from each element of the
# list.
result_.columns = [column_name.strip() for column_name in columns_]

# Printing the column names of the dataframe.
print(result_.columns.values)

# ['姓名' '年龄' '班级' '成绩' '表现']

经过数据清洗后,发现所有的列名称空格情况已经被全部清洗了。若是存在某个列中的值空格需要清洗也可以采用strip函数进行清洗。

2. duplicated函数清除重复数据

关于重复数据的判断有两种情况,一种是两行完全相同的数据即为重复数据。另外一种则是部分相同指的是某个列的数据是相同的需要清洗。

# The `duplicated()` function is returning a boolean series that is True if the row is a duplicate and False if the row is
# not a duplicate.
repeat_num = result_.duplicated().sum()

# Printing the number of duplicate rows in the dataframe.
print(repeat_num)

# 1

通过上面的duplicated().sum()函数得到的是两个完全相同的数据行是多少。

接着则可以对源数据进行实际意义上的删除,使用DataFrame对象的drop_duplicates函数进行删除。

# The `drop_duplicates()` function is dropping the duplicate rows from the dataframe and the `inplace=True` is
# modifying the dataframe in place.
result_.drop_duplicates(inplace=True)

# Printing the dataframe.
print(result_)

#            姓名  年龄    班级   成绩 表现
# 0   Python 集中营  10  1210   99  A
# 1   Python 集中营  11  1211  100  A
# 2   Python 集中营  12  1212  101  A
# 3   Python 集中营  13  1213  102  A
# 4   Python 集中营  14  1214  103  A
# 5   Python 集中营  15  1215  104  A
# 6   Python 集中营  16  1216  105  A
# 7   Python 集中营  17  1217  106  A
# 8   Python 集中营  18  1218  107  A
# 9   Python 集中营  19  1219  108  A
# 10  Python 集中营  20  1220  109  A
# 11  Python 集中营  21  1221  110  A
# 12  Python 集中营  22  1222  111  A
# 13  Python 集中营  23  1223  112  A
# 14  Python 集中营  24  1224  113  A
# 15  Python 集中营  25  1225  114  A
# 16  Python 集中营  26  1226  115  A
# 17  Python 集中营  27  1227  116  A

因为最后一行和第一行的数据是完全相同的,因此最后一行的数据已经被清洗掉了。

一般在数据清洗删除重复值之后需要重置索引,避免索引产生不连续性。

# The `range(result_.shape[0])` is creating a list of numbers from 0 to the number of rows in the dataframe.
result_.index = range(result_.shape[0])

# The `print(result_.index)` is printing the index of the dataframe.
print(result_.index)

# RangeIndex(start=0, stop=18, step=1)

3. 数据缺失值补全

一般查看DataFrame数据对象的缺失值就是通过使用isnull函数来提取所有数据缺失的部分。

# The `isnull()` function is returning a boolean series that is True if the value is missing and False if the value
# is not missing.
sul_ = result_.isnull()

# The `print(sul_)` is printing the boolean series that is True if the value is missing and False if the value is not
# missing.
print(sul_)

#        姓名     年龄     班级     成绩     表现
# 0   False  False  False  False  False
# 1   False  False  False  False  False
# 2   False  False  False  False  False
# 3   False  False  False  False  False
# 4   False  False  False  False  False
# 5   False  False  False  False  False
# 6   False  False  False  False  False
# 7   False  False  False  False  False
# 8   False  False  False  False  False
# 9   False  False  False  False  False
# 10  False  False  False  False  False
# 11  False  False  False  False  False
# 12  False  False  False  False  False
# 13  False  False  False  False  False
# 14  False  False  False  False  False
# 15  False  False  False  False  False
# 16  False  False  False  False  False
# 17  False  False  False  False  False

返回的每一个单元格数据结果为False则代表这个单元格的数据是没有缺失的,或者也可以使用notnull来反向查看。

使用isnull函数不想显示很多的列表数据时,可以使用sum函数进行统计。

# The `isnull_sum = result_.isnull().sum()` is returning a series that is the sum of the boolean series that is True if
# the value is missing and False if the value is not missing.
isnull_sum = result_.isnull().sum()

# The `isnull_sum = result_.isnull().sum()` is returning a series that is the sum of the boolean series that is True if
# the value is missing and False if the value is not missing.
print(isnull_sum)

# 姓名    0
# 年龄    0
# 班级    0
# 成绩    0
# 表现    0
# dtype: int64

通过isnull函数处理后使用sum函数进行统计,统计后会返回每一列的数据单元格为空的个数。

接下来就是数据值的填补过程,通常可以筛选每一列中的空值填补固定的数据。

# The `result_.loc[result_.姓名.isnull(), '姓名']` is returning a series that is the values of the column `姓名`
# where the values are missing. The `'Python 集中营'` is the value that is being assigned to the series.
result_.loc[result_.姓名.isnull(), '姓名'] = 'Python 集中营'

# Printing the dataframe.
print(result_)

#             姓名  年龄    班级   成绩 表现
# 0   Python 集中营  10  1210   99  A
# 1   Python 集中营  11  1211  100  A
# 2   Python 集中营  12  1212  101  A
# 3   Python 集中营  13  1213  102  A
# 4   Python 集中营  14  1214  103  A
# 5   Python 集中营  15  1215  104  A
# 6   Python 集中营  16  1216  105  A
# 7   Python 集中营  17  1217  106  A
# 8   Python 集中营  18  1218  107  A
# 9   Python 集中营  19  1219  108  A
# 10  Python 集中营  20  1220  109  A
# 11  Python 集中营  21  1221  110  A
# 12  Python 集中营  22  1222  111  A
# 13  Python 集中营  23  1223  112  A
# 14  Python 集中营  24  1224  113  A
# 15  Python 集中营  25  1225  114  A
# 16  Python 集中营  26  1226  115  A
# 17  Python 集中营  27  1227  116  A

4. 数据保存

数据清洗完成之后,可以使用DataFrame对象提供的to_csv/to_excel等函数进行特定格式的数据保存。

result_.to_excel('data.xlsx')

最后,整个数据清洗的过程就完成了,希望可以给大家带来帮助,感谢阅读!

相关推荐

工程师必备!DeepSeek自动化运维全攻略

每天省出3小时,故障自修复+智能监控实战指南导语“总在深夜被报警短信吵醒?教你搭建智能运维体系,让DeepSeek自己管自己!”正文技能1:自动化故障诊断配置智能诊断规则:yaml复制alert_ru...

Spug - 轻量级自动化运维平台(自动化运维平台 devops)

对于中小型企业而言,进行主机和应用的管理是比较麻烦的,应用部署往往需要直接连接服务器,再进行手动的环境配置、代码拉取、应用构建和部署发布等工作,容易出错,且耗时费力。一个好的自动化运维平台,往往能大大...

轻量级无 Agent 的一个好用的“小麻雀”自动化运维平台工具!-Spug

对于中小型企业而言,进行主机和应用的管理是比较麻烦的,应用部署往往需要直接连接服务器,再进行手动的环境配置、代码拉取、应用构建和部署发布等工作,容易出错,且耗时费力。一个好的自动化运维平台,往往能大大...

运维自动化之实用python代码汇总(python自动化运维常用模块)

本文总结了运维工作中经常用到的一些实用代码块,方便在需要的时候直接搬过来使用即可1.执行系统命令,获取返回结果fromsubprocessimportPopen,PIPE,STDOUTcp...

从代码小白到自动化大师:Python 编程实战

昨天我聊了一下关于线性代数、概率统计、微积分核心概念的学习,也花了一些时间恢复一下大学时候学这些的记忆,确实来说数学很有趣也很考验人,兴趣是最好的老师对吧,既然对AI感兴趣,总要认真的学一学,接下来我...

锐捷:基于Python TextFSM模块的网络设备自动化运维方法

网络设备自动化运维,首先要实现网络设备与自动化运维平台对接,即通过代码实现登录网络设备并获取信息。邮政业科技创新战略联盟单位锐捷自主研发的数据中心交换机产品已全面支持NETCONF协议,可适用于和SD...

基于Python+vue的自动化运维、完全开源的云管理平台

真正的大师,永远都怀着一颗学徒的心!一、项目简介今天说的这个软件是一款基于Python+vue的自动化运维、完全开源的云管理平台。二、实现功能基于RBAC权限系统录像回放DNS管理配置中心强大的作业调...

编程与数学:在Python里怎么用turtle库函数填色?

这里只给出一个示例,一个最简单的示例。看懂这个示例,你就能在自己的代码里需要填色的地方填色。首先,与前面发的Python绘画程序一样,先要装入turtle库。然后在代码中,下面需要填色时,先写一个填色...

Python UV 环境下的 PyKDL 运动学库安装

视频讲解:PythonUV环境下的PyKDL运动学库安装_哔哩哔哩_bilibilimujoco-learning这个仓库,改成uv管理环境依赖后,原来的一些包有些缺失,比如之前安装的PyKD...

python最新版3.11正式发布,有哪些新特色?(3/5)

异步任务的语法更完美python编程语言对异步编程的支持一直在改进,比如python2.0版开始就增加了生成器(generator),在3.4版开始增加了asyncio库,随后在3.5版中...

清华北大都在用!Python王者归来(全彩版)

纸上得来终觉浅,绝知此事要躬行。今天给大家带来一份由清华大学出版的《python王者归来》。在当下全民互联网,大数据的时代,Python已然成为了学习大数据、人工智能时代的首选编程语言,Python...

第六章:Python模块与包(python模块与包与类的关系区别)

6.1模块基础6.1.1理论知识模块是一个包含Python定义和语句的文件,其扩展名为.py。模块可以将代码组织成逻辑单元,提高代码的可维护性和复用性。通过将相关的函数、类和变量放在同一个模块中...

语言教育项目实战之一:Ubuntu下安装Python环境

如下项目,运行在#ubuntu#上,使用#pytho#,从最初环境开始,逐渐深入。此项目以语言学习为主要目的,实现听写、跟读、对话的服务,面向中小学生、大学生、涉外交流人员等。计划通过pyenv管...

openai-python v1.79.0重磅发布!全新Evals API升级,音频转录终极

2025年5月17日,OpenAI官方在GitHub上发布了openai-python库的最新版本——v1.79.0。本次版本重点围绕Evals评估API进行了多项功能完善,同时修复了音频转录接口的重...

你真的用对了吗?7个常被误用的Python内置函数及最佳实践

你是否曾经在使用多年的工具中突然发现一个新功能,然后感叹:“我怎么一直没发现这个?”没错,今天我们就来体验一把“Python函数版”的这种乐趣。这些函数很可能已经是你日常代码的一部分,但我敢打赌,你并...

取消回复欢迎 发表评论: