首页 > 解决方案 > 从文件名中提取日期并添加为列

问题描述

我有多个文件要制作成 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

标签: pythonpandasre

解决方案


用于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

推荐阅读