python 数据的清理行为实例详解

yipeiwu_com6年前Python基础

python 数据的清理行为实例详解

数据清洗主要是指填充缺失数据,消除噪声数据等操作,主要还是通过分析“脏数据”产生的原因和存在形式,利用现有的数据挖掘手段去清洗“脏数据”,然后转化为满足数据质量要求或者是应用要求的数据。

1、try 语句还有另外一个可选的子句,它定义了无论在任何情况下都会执行的清理行为

例如:

>>>try:
raiseKeyboardInterrupt
finally:
print('Goodbye, world!')
Goodbye, world!
Traceback(most recent call last):
File"<pyshell#71>", line 2,in<module>
raiseKeyboardInterrupt
KeyboardInterrupt

以上例子不管try子句里面有没有发生异常,finally子句都会执行。 

2、如果一个异常在 try 子句里(或者在 except 和 else 子句里)被抛出,而又没有任何的 except 把它截住,那么这个异常会在 finally 子句执行后再次被抛出。

下面是一个更加复杂的例子(在同一个 try 语句里包含 except 和 finally 子句):

>>>def divide(x, y):
try:
 result = x / y
exceptZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
>>> divide(2,1)
result is2.0
executing finally clause
>>> divide(2,0)
division by zero!
executing finally clause
>>> divide("2","1")
executing finally clause
Traceback(most recent call last):
File"<pyshell#91>", line 1,in<module>
  divide("2","1")
File"<pyshell#88>", line 3,in divide

 3、预定义的清理行为

一些对象定义了标准的清理行为,无论系统是否成功的使用了它,一旦不需要它了,那么这个标准的清理行为就会执行。
这面这个例子展示了尝试打开一个文件,然后把内容打印到屏幕上:

>>>for line in open("myfile.txt"):
print(line, end="")
Traceback(most recent call last):
File"<pyshell#94>", line 1,in<module>
for line in open("myfile.txt"):
FileNotFoundError:[Errno2]No such file or directory:'myfile.txt'

以上这段代码的问题是,当执行完毕后,文件会保持打开状态,并没有被关闭。

关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法:

>>>with open("myfile.txt")as f:
for line in f:
print(line, end="")
Traceback(most recent call last):
File"<pyshell#98>", line 1,in<module>
with open("myfile.txt")as f:
FileNotFoundError:[Errno2]No such file or directory:'myfile.txt'

以上这段代码执行完毕后,就算在处理过程中出问题了,文件 f 总是会关闭。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

pytorch:torch.mm()和torch.matmul()的使用

如下所示: torch.mm(mat1, mat2, out=None) → Tensor torch.matmul(mat1, mat2, out=None) → Tensor...

python中的字典详细介绍

一、什么是字典? 字典是Python语言中唯一的映射类型。 映射类型对象里哈希值(键,key)和指向的对象(值,value)是一对多的的关系,通常被认为是可变的哈希表。 字典对象是可变的...

python 实现矩阵填充0的例子

需求: 原矩阵 [[1 2 3] [4 5 6] [7 8 9]] 在原矩阵元素之间填充元素 0,得到 [[1. 0. 2. 0. 3.] [0. 0. 0. 0. 0....

Pytorch的mean和std调查实例

如下所示: # coding: utf-8 from __future__ import print_function import copy import click impor...

python清除函数占用的内存方法

python升级到2.7.13 函数执行的结尾加上这个即可 for x in locals().keys(): del locals()[x] gc.collect() 原理是...