python - 从文件名中提取日期并添加为列
问题描述
我有多个文件要制作成 df 并合并/附加到单个 df 中。这些文件具有共同的文件名模式,即“SWAT [Jan 01,2026]^URTW_L3 的平均地图”。我已经通过阅读所有文件来管理并附加到一个文件中,并添加了带有文件名的列。但是,对于如何在列中而不是完整文件名中包含日期 [Jan 01, 2026] 感到困惑。本质上,想要将文件名中的日期提取到附加的最终 df 中的日期时间格式列中。正则表达式方法是首选,因为我想学习如何。
import glob
import os
import re
import pandas as pd
myfiles = glob.glob("C:\\Users\\x\\AnacondaProjects\\VORONOI\\test\\*")
col_names = ['X','Y','SW','i']
df = pd.DataFrame()
for file_ in myfiles:
file_df = pd.read_csv(file_,sep=' ',names=col_names, header=None)
file__=os.path.split(file_)
file_df['file_name'] = file__[1]
df = df.append(file_df)
df.to_csv('merged.csv',index=False,header=True)
Exampe of df so far:-
X Y SW i file_name
4 3 1 1 average map for SWAT [Jan 01,2026]^URTW_L3
2 1 1 2 average map for SWAT [Jan 01,2027]^URTW_L3
解决方案
用于extract
获取方括号之间的字符串,然后将其转换为时间戳:
date = df['file_name'].str.extract(r'\[(.+)\]', expand=False)
df['date'] = pd.to_datetime(date, format='%b %d,%Y')
print(df)
X Y SW i file_name date
0 4 3 1 1 average map for SWAT [Jan 01,2026]^URTW_L3 2026-01-01
1 2 1 1 2 average map for SWAT [Jan 01,2027]^URTW_L3 2027-01-01
推荐阅读
- java - 如何重构在 Java 中有重复模式的代码?
- git - 无法将更改从我的终端推送到 GitHub
- unix - 如何删除文件中某些行中的特定字符?
- php - 在对 2 个或多个整数执行加法时获取所有进位数字的总和
- php - 预期类型“可迭代|对象”。找到“字符串”但不明白为什么
- python - 如何编辑此代码以便输入 GIF 文件?它允许我使用 JPG 和 PNG,但不能使用 GIF
- ios - Swift UI 列表未在 Cloudkit 同步时更新
- php - PHP Server 在 Heroku 的 json 中返回错误
- java - 为 MediaStore.createTrashRequest 函数创建 Uri
- python - Binance API:APIError(code=-1111):精度超过了为该资产定义的最大值。|| Python