我在我的文件夹中有一组文件,想要在文件名中捕获日期,并在阅读Pandas Data Frame时将其添加到列中。
我的文件名如-X_04_24_2018.txt Y_04_25_2018.txt Z_04_26_2018.txt
假设该文件有2列,其中包含样本内容,我需要一个具有以下格式的数据框。感谢您对此的帮助。
Col1 Col2 Date File
XXX ABC 4/24/2018 X
YYY BCA 4/25/2018 Y
ZZZ CBA 4/26/2018 Z
一种方法是使用os.path
的字典理解来从文件名列表中提取相关细节。
然后使用另一个字典理解来读取文件,使用pd.DataFrame.assign
分配相关列。
from os import path
import pandas as pd
files = ['X_04_24_2018.txt', 'Y_04_25_2018.txt', 'Z_04_26_2018.txt']
att = {files[idx]: [i[0][:-11], i[0][-10:].replace('_', '/')]
for idx, i in enumerate(map(path.splitext, files))}
dfs = {f: pd.read_csv(f).assign(Date=att[f][1], File=att[f[0]]) for f in files}