A detailed example of python data cleansing behavior

  • 2020-06-07 04:51:16
  • OfStack

A detailed example of python data cleansing behavior

Data cleaning mainly refers to operations such as filling in missing data and eliminating noise data. It mainly USES existing data mining methods to clean "dirty data" by analyzing the causes and forms of "dirty data", and then converts the data into data that meets the requirements of data quality or application.

1. The try statement has another optional clause that defines the cleanup that will be performed under any circumstances.

Such as:


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

In the above example, the finally clause executes regardless of whether an exception occurs in the try clause.

2. If an exception is thrown in the try clause (or in the except and else clauses) and no except intercepts it, the exception is thrown again after the finally clause.

Here is a more complex example (including the except and finally clauses in the same try statement) :


>>>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. Predefined cleaning behavior

1 objects define the standard cleanup behavior, and once it is no longer needed, the standard cleanup behavior is performed, regardless of whether the system successfully USES it.
This example shows trying to open a file and print the contents onto the screen:


>>>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'

The problem with this code is that when executed, the file remains open, not closed.

The key word with statement ensures that objects such as files will perform their cleanup correctly after use:


>>>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'

After the above code is executed, the file f always closes, even if something goes wrong during processing.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: