python-3.x - 并排排列文本文件以制作矩阵文件
问题描述
我在一个目录中有 3000 个文本文件,每个 .txt 文件都包含单列数据。我想将它们并排排列以使其成为 mxn 矩阵文件。
为此我尝试了
printf "%s\n" *.txt | sort -n | xargs -d '\n' paste
但是它给出了错误粘贴:filename.txt:打开的文件太多
请使用python为相同的问题提出更好的解决方案。
解决方案
对于在文本文件的第一行中包含唯一列名称的相对较短的文件,您可以执行以下操作:
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,每个文件都是一列。
推荐阅读
- javascript - 了解 Javascript 如何全局解析变量
- google-app-engine - 从外部 URL 加载 Freemarker 模板
- c++ - CGAL:与半边相关的刻面的输出 ID
- javascript - React-select:背景颜色不会在 wordWrap 上填满全宽:“scroll”
- node.js - Mongoose 按参考 ID 查找
- git - 当存储库与共享库相同时,Jenkins 不会检查正确的版本
- qt - 如何在 QML 中制作 3D 文本
- java - 如何从 cURL 命令或 Internet 浏览器通过 HTTP/1.1 调用 gRPC 服务器
- android - 无法解析符号登录 Android Studio 3.4.1
- python - TF keras API 与 TF 数据集问题 - steps_per_epoch 参数问题