简体   繁体   中英

How to handle ParserError in Python?

My data contains several dates in different format:

event team1 team2
practice 7/16/2022 7/18
gameday July 17 2022 showtime

I am trying to convert all dates into the same format(ie 07/16/2022) using parser.parse, but I'm getting ParseError when the date is 'showtime'. How can I handle ParserError and replace the non-date input into a random date('showtime' into random date mm/dd/yyyy)? Thank you.

from dateutil.parser import parse

df['team1'] = parse(df['team1'])
df['team2'] = parse(df['team2'])

This isn't too elegant and may miss additional edge cases for odd dates, but maybe this will help with your immediate issue as long as missing years will be assumed to be 2022 for example.

import pandas as pd


year = "2022"
data = {
    "event": ["practice", "gameday"],
    "team1": ["7/16/2022", "July 17 2022"],
    "team2": ["7/18", "showtime"]
}
df = pd.DataFrame(data)


for column in ["team1", "team2"]:
    df[column] = df[column].apply(
        lambda x: pd.to_datetime(x if year in x else f"{x}/{year}", errors="coerce")
    ).map(lambda x: x.strftime("%m/%d/%Y") if pd.notnull(x) else "")

print(df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM