首页 > 解决方案 > 并排排列文本文件以制作矩阵文件

问题描述

我在一个目录中有 3000 个文本文件,每个 .txt 文件都包含单列数据。我想将它们并排排列以使其成为 mxn 矩阵文件。

为此我尝试了

printf "%s\n" *.txt | sort -n | xargs -d '\n' paste

但是它给出了错误粘贴:filename.txt:打开的文件太多

请使用python为相同的问题提出更好的解决方案。

标签: python-3.xpandasnumpyjoin

解决方案


对于在文本文件的第一行中包含唯一列名称的相对较短的文件,您可以执行以下操作:

import pandas as pd
from pathlib import Path 

def listFiles(ddir):
    #return a list of txt files in the file directory specified by ddir
    p = Path(ddir)
    return list(p.glob('*.txt'))  

def readfile_toDataframe(file):
    #create a dataframe from the contents of file
    return pd.read_csv(file)

def joinDfs(list_of_files):
    # Read a list of files and join their contents on the index
    dfo = readfile_toDataframe(list_of_files[0])
    for f in list_of_files[1:]:
        dfo = dfo.join(readfile_toDataframe(f))
    return dfo  

通过运行:

joinDFs(listFiles(ddir))  

其中 ddir 是指向文件目录的字符串变量,您将读取文件并创建其内容的 DataFrame,每个文件都是一列。


推荐阅读