将许多 txt/csv 个文件编译成一个数据框,并将文件名添加为一列
Compiling many txt/csv files into a single dataframe with filename added as a column
我正在努力编译许多文件并同时将文件名作为列添加到生成的数据框中。以下脚本有效,但不知何故只对单个文件执行操作...为什么不能将所有文件放在一起?
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 行乘以两列(波长和值),我现在正在使用 assign(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)
我正在努力编译许多文件并同时将文件名作为列添加到生成的数据框中。以下脚本有效,但不知何故只对单个文件执行操作...为什么不能将所有文件放在一起?
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 行乘以两列(波长和值),我现在正在使用 assign(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)