python - 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'))
解决方案
您可以直接使用 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')
推荐阅读
- python - 是否可以将我的样式设置为我的非 gui python 代码并给它一个好看的外观?
- apache-spark - 关于“spark.sql.objectHashAggregate.sortBased.fallbackThreshold”
- javascript - 如何将电子邮件数据集转换为旭日形图的层次结构?
- android - 使用 Apps 脚本创建的全天事件未在 Android Google 日历应用中显示
- c# - System.NullReferenceException:“对象引用未设置为对象的实例。” 组合框选定的项目
- flutter - Flutter:允许用户发送邀请邮件
- c# - 如何使用 SelectToken 从 Json 中获取特定值
- python - 如何在安装 bcrypt 时修复 pypy3 错误?
- android - 有主键时如何在Android中使用Dao Room将列表插入到表中
- thymeleaf - 在 XML 中使用 CDATA 换行文本