python-3.xstring-to-datetime

Apply lambda function to list of columns in pandas dataframe


I have a large dataframe from csv (170 cols). Many of these are date but not being read as date. I have a list of these as

date_cols = [col for col in df.columns if 'date' in col] I want to apply a function to all those columns (13 total) How can i apply a function over that list. Attempted so far:

modDfObj = df.apply(lambda x: pd.to_datetime(x) if x.name in date_cols else x)


Solution

  • via filter and applymap

    df = df.filter(like='date').applymap(lambda x: pd.to_datetime(x, errors='coerce'))
    

    Updated:

    date_cols = [col for col in df.columns if 'date' in col]
    df[date_cols] = df[date_cols].applymap(lambda x: pd.to_datetime(x, errors='coerce'))