我正在努力编译许多文件,并同时将文件名作为结果数据框中的列添加。以下脚本可以工作,但不知何故仅对单个文件执行操作...为什么这不将所有文件放在一起?
import glob
import pandas as pd
import os
# format Working but only reads 1 file
indir = "C:\\location\test"
outfile = "C:\\location\test\output.csv"
# Change the directory to where the files are located
os.chdir(indir)
# Make an empty list
filelist = []
# Populate list with filenames. structure criteria with wild cards
for files in glob.glob('*.txt'):
filelist.append(files)
print(filelist) # so far so good, all files are in the list
# apply a for loop to the files listed above by glob
for files in filelist:
# built up dataframes and append the filepath as a column
frame = [pd.read_csv(files, skiprows=21, header=None,
delim_whitespace=True).assign(Filename=os.path.basename(files))]
df = pd.concat(frame, ignore_index=True)
df.columns = ['Wavelength', 'Value', 'Filename']
df.to_csv(outfile, index=None)
print(df)
我知道已经有一些线程正在处理类似的问题,但这些线程以某种方式让我到达了这个特定的砖墙。
顺便说一下,源文件的形状是 2256 行 x 两列(波长和值),目前我正在使用 allocate(Filename=os.path.basename()) 添加文件名列。
最佳答案
您正在将 for
循环与列表理解码合/混淆。选择其中之一(而不是两者)来迭代 filelist
。此外,您的串联应该发生在 for
循环或列表理解之外。
例如,在这里,您可以使用列表理解,然后将其提供给 pd.concat
:
filelist = list(glob.glob('*.txt'))
frames = [pd.read_csv(fp, skiprows=21, header=None, delim_whitespace=True)\
.assign(Filename=os.path.basename(fp)) for fp in filelist]
df = pd.concat(frames, ignore_index=True)
df.columns = ['Wavelength', 'Value', 'Filename']
df.to_csv(outfile, index=None)
关于python - 将许多 txt/csv 文件编译成单个数据框,并将文件名添加为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51899774/