如何在 try 和 except 使用 python 中获取导致行的错误?
How to get the error causing rows in try and except using python?
我是 python 的新手。我正在寻找一种方法来将导致行的错误放入新的数据框中。因此,我有一个数据框,我想从中检查日期列是否采用特定日期格式。虽然我已经编写了代码并使输出正确,但我想将导致行的错误放入新的数据框中。我该怎么做?
我的代码:
df =
Date cars
0 2020-01-02 two
1 01-02-2020 three
3 01022020 four
4 080920201 five
import dateutil.parser
for row in df.Date:
try:
valid = dateutil.parser.parse(row)
print(valid)
except ValueError:
invaild = "error caused row"
print(invalid)
预期输出:
valid
0 2020-01-02 00:00:00
1 2020-01-02 00:00:00
3 2020-01-02 00:00:00
Invaild
4 080920201 five
要根据行是否有效打印不同的内容,请在 try 子句 或 except 子句 中打印它:
for row in df.Date:
try:
valid = dateutil.parser.parse(row)
print(row, "was a valid row")
except ValueError:
print(row, "caused an error")
或者要收集列表中导致错误的所有行,请在 except 子句中调用列表 append
方法:
invalid_rows = []
for row in df.Date:
try:
valid = dateutil.parser.parse(row)
except ValueError:
invalid_rows.append(row)
见https://docs.python.org/3/tutorial/errors.html#handling-exceptions:
The try statement works as follows.
First, the try clause (the statement(s) between the try
and except
keywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try
statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named
after the except
keyword, the except clause is executed, and then
execution continues after the try
statement.
我是 python 的新手。我正在寻找一种方法来将导致行的错误放入新的数据框中。因此,我有一个数据框,我想从中检查日期列是否采用特定日期格式。虽然我已经编写了代码并使输出正确,但我想将导致行的错误放入新的数据框中。我该怎么做?
我的代码:
df =
Date cars
0 2020-01-02 two
1 01-02-2020 three
3 01022020 four
4 080920201 five
import dateutil.parser
for row in df.Date:
try:
valid = dateutil.parser.parse(row)
print(valid)
except ValueError:
invaild = "error caused row"
print(invalid)
预期输出:
valid
0 2020-01-02 00:00:00
1 2020-01-02 00:00:00
3 2020-01-02 00:00:00
Invaild
4 080920201 five
要根据行是否有效打印不同的内容,请在 try 子句 或 except 子句 中打印它:
for row in df.Date:
try:
valid = dateutil.parser.parse(row)
print(row, "was a valid row")
except ValueError:
print(row, "caused an error")
或者要收集列表中导致错误的所有行,请在 except 子句中调用列表 append
方法:
invalid_rows = []
for row in df.Date:
try:
valid = dateutil.parser.parse(row)
except ValueError:
invalid_rows.append(row)
见https://docs.python.org/3/tutorial/errors.html#handling-exceptions:
The try statement works as follows.
First, the try clause (the statement(s) between the
try
andexcept
keywords) is executed.If no exception occurs, the except clause is skipped and execution of the
try
statement is finished.If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the
except
keyword, the except clause is executed, and then execution continues after thetry
statement.