简体   繁体   中英

Try and except in a loop python

I wonder whether it is possible to improve this code with "try and except" in a loop as below. The idea is to change format if a certain column is included in a df.

Thank a lot.

for field in ['Trade Date', 'Capture Date', 'Value Date', 'Maturity Date','Start Date', 'End Date', 'Payment Date']:
try:
    FXS_deals[field] = pd.to_datetime(FXS_deals[field], format = '%d/%m/%Y')
except Exception:
    pass
try:
    FWD_deals[field] = pd.to_datetime(FWD_deals[field], format = '%d/%m/%Y')
except Exception:
    pass
try:
    SPOT_deals[field] = pd.to_datetime(SPOT_deals[field], format = '%d/%m/%Y') 
except Exception:
    pass
try:
    LD_deals[field] = pd.to_datetime(LD_deals[field], format = '%d/%m/%Y') 
except Exception:
    pass

I think this would be neater:

DEALS = [FXS_Deals, FWD_Deals, SPOT_Deals, LD_Deals]

for field in ['Trade Date', 'Capture Date', 'Value Date', 'Maturity Date','Start Date', 'End Date', 'Payment Date']:
    for d in DEALS:
        try:
            d[field] = pd.to_datetime(d[field], format = '%d/%m/%Y')
        except (ValueError, pd.errors.ParserError):
            pass
def test_format(data, field):
    try:
        return pd.to_datetime(data[field], format='%d/%m/%Y')
    except Exception:
        pass
    return None


my_data = [FXS_deals, FWD_deals, SPOT_deals, LD_deals]
for field in ['Trade Date', 'Capture Date', 'Value Date', 'Maturity Date', 'Start Date', 'End Date', 'Payment Date']:
    for data in my_data:
        result = test_format(data, field)
        if result:
            data[field] = result

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