1

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)

mapping dom
  • 1,737
  • 4
  • 27
  • 50

1 Answers1

1

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'))
Nk03
  • 14,699
  • 2
  • 8
  • 22
  • That works but only returns a reduced data frame, can i return the full df with date columns converted in place? – mapping dom May 12 '21 at 16:32