python - 将许多 txt/csv 文件编译成单个数据框,并将文件名添加为列

标签 python list pandas csv glob

我正在努力编译许多文件,并同时将文件名作为结果数据框中的列添加。以下脚本可以工作,但不知何故仅对单个文件执行操作...为什么这不将所有文件放在一起?

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/

相关文章:

c# - 继承自列表<T>

python - 从列表中提取与第三个列表中包含的另一个列表的项目具有相同索引的值

python - 在 Python 中禁用 subprocess.Popen 的控制台输出

Java8 列表<T> 到列表<object[]>

python - Pandas - 将具有多列的数据框 reshape /转换为单列值

python - 基于DataFrame列的操作

python - 根据索引将数据帧除以另一个数据帧

python - 打印用 Python 读入的文件的最后一行

python - 您可以使用流而不是本地文件上传到 S3 吗?

python - 使用 Python 时的 BadStatusLine 错误,请求