python 应用函数但忽略不在索引中的列

python apply function but ignore columns if not in index

我有 3 个数据框,每个数据框至少有 1 列需要转换为 datetime64

times = ['time1','time2','time3']

我有这个功能-

def cols_to_datetime(df, cols=None):
    if not cols:
        
        cols = times
    df[cols] = df[cols].astype('datetime64')
    return df

然后运行3个dfs通过这个,但是df3只有time1。如果其中一个 dfs 没有所有时间列,我如何保留所有三个时间列但忽略索引错误?

time_cols = ['time1', 'time2', 'time3']
def cols_to_datetime(df, cols=None):
    if not cols:
        # only take the column names that are present in df.columns
        cols = [tcol for tcol in time_cols if tcol in df.columns]
    df[cols] = df[cols].astype('datetime64')
    return df