当读取多个csv文件时,将文件名附加到列头



我想读取多个.csv文件,并将其文件名的datetime部分附加到列标题。每个csv文件都包含在特定日期时间获取的数据。每个文件名有以下格式:

yyyy-mm-dd_hh-mm-ss_someothertext

每个文件只包含一列数据。

我成功导入了多个文件作为数据帧列表,如下所示:

import pandas as pd
import glob
path = r'C:Users...' #path
all_files = glob.glob(path + "/*.csv")
li = []
for filename in all_files:
df = pd.read_csv(filename, index_col=None, header=0)
li.append(df)

然后我将这些文件连接到一个数据框中,这样每一列都包含来自其中一个文件的数据:

frame = pd.concat(li, axis=1, ignore_index=True)

然而,这就是我丢失文件名信息的地方。列标题现在只是一系列数字。我的问题是:我如何将每个文件名的日期时间部分附加到frame中各自的列标题?

我得到的最接近的是能够附加整个文件名,而不仅仅是日期时间部分,通过转置frame以迂回的方式,将整个文件名添加为新列,转置回来,然后将文件名行设置为标题行…

import os
frame=pd.DataFrame.transpose(frame)
frame['filename'] = os.path.basename(filename)
frame=pd.DataFrame.transpose(frame)
frame.reset_index(drop=True)
frame.columns = frame.iloc[6628] #row 6628 is where the row with the filenames ends up after transposing

这似乎非常低效,但最终以整个文件名作为头,而不仅仅是datetime部分。

这是我建议的方法,压缩DataFrame并使用Regex:

import re
import os
import glob
import pandas as pd
path = 'C:Users....'
files = glob.glob(f'{path}*.csv')
li = []
for file in files:
name = os.path.basename(file)  # get filename
date = re.search(r'd{4}-d{2}-d{2}', name).group(0)  # extract yyyy-mm-dd from filename
# read file, squeeze to Series, rename to date
li.append(pd.read_csv(file, index_col=None, header=0, squeeze=True).rename(date))  
frame = pd.concat(li, axis=1, ignore_index=False)

最新更新