首页 > 解决方案 > Python:如何在单个循环中格式化多个数据框的日期列

问题描述

在 Python 中,我有 5 个不同的数据框:stock_df, ltb_df, stb_df, gld_df, comms_df

我想在一个循环'Date'中格式化所有 5 个数据帧的列,而不是在下面的代码中逐一输入它们。我该怎么办?

import pandas as pd

stock_df['Date'] = pd.to_datetime(stock_df['Date'], format='%m/%d/%Y %H:%M:%S')\
                .apply(lambda x: x.strftime('%Y-%m-%d'))
ltb_df['Date'] = pd.to_datetime(ltb_df['Date'], format='%m/%d/%Y %H:%M:%S')\
                .apply(lambda x: x.strftime('%Y-%m-%d'))
stb_df['Date'] = pd.to_datetime(stb_df['Date'], format='%m/%d/%Y %H:%M:%S')\
                .apply(lambda x: x.strftime('%Y-%m-%d'))
gld_df['Date'] = pd.to_datetime(gld_df['Date'], format='%m/%d/%Y %H:%M:%S')\
                .apply(lambda x: x.strftime('%Y-%m-%d'))
comms_df['Date'] = pd.to_datetime(comms_df['Date'], format='%m/%d/%Y %H:%M:%S')\
                .apply(lambda x: x.strftime('%Y-%m-%d'))

标签: pythonpandas

解决方案


您可以直接使用 useSeries.dt.strftime而不是 usingapply方法。

采用:

dfs = [stock_df, ltb_df, stb_df, gld_df, comms_df]
for df in dfs:
    df["Date"] = pd.to_datetime(df['Date'], format='%m/%d/%Y %H:%M:%S').dt.strftime('%Y-%m-%d')

推荐阅读