我正在尝试将通过 read_csv 作为对象的一些列转换为_datetime。到目前为止,列名始终包含术语 DATE、_DT 或时间戳。如果我要转换的系列在列表中,我不确定如何正确处理它。
date_col = [col for col in list(df) if re.search('DATE', col)]
dt_col = [col for col in list(df) if re.search('_DT', col)]
ts_col = [col for col in list(df) if re.search('TIMESTAMP', col)]
dt_cols = date_col + dt_col + ts_col
for col in list(df):
if col in dt_cols:
col = pd.to_datetime(col)
这对于未知的字符串格式失败,据我所知,这是由引用列表中的字符串引起的。我不确定我需要在 pd.to_datetime 中放置什么以在循环的每次迭代中适本地引用系列。
请您参考如下方法:
试试这个:
PATTERN = r'DATE|_DT|TIMESTAMP'
date_cols = [c for c in df.columns if re.search(PATTERN, c)]
for col_name in date_cols:
df[col_name] = pd.to_datetime(df[col_name])
如果您有列名列表,则遍历更新每一列。
