How to get the error causing rows in try and except using python?

I am new to python. I am looking for a way to get the error causing rows into a new data frame. So, I have a data frame from where I want to check if a date column is in a particular date format or not. Though I have written the code and getting the output correct, I want to get the error causing rows into a new data frame. How do I do it?

My code:

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)

Execpted output:

    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

Answer

To print something different, depending on whether a row was valid, print it either in the try clause or in the except clause:

for row in df.Date:
    try:
        valid = dateutil.parser.parse(row)
        print(row, "was a valid row")
    except ValueError:
        print(row, "caused an error")

Or to collect all rows causing an error in a list, call the list append method inside the except clause:

invalid_rows = []
for row in df.Date:
    try:
        valid = dateutil.parser.parse(row)
    except ValueError:
        invalid_rows.append(row)

See 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.

Leave a Reply

Your email address will not be published. Required fields are marked *