繁体   English   中英

使用 Pandas 或 Python 逐行合并两个文件

[英]Merging two files line by line using Pandas or Python

我有两个文件(示例:A.txt 和 B.txt),其中“A.txt”非常大。 我想避免将完整文件读入 memory,并在合并来自“B.txt”的匹配之前逐行读取。 这两个文件也有标题。

我当前的代码如下所示:

import os
import pandas as pd

contigs=pd.read_csv("A.txt", header=0, sep="\t")
coverages=pd.read_csv("B.txt", header=0, sep="\t")
merged=pd.merge(contigs, coverages, on='contig')
merged.to_csv("merged_file.txt", sep="\t", index=False)

该代码有效,但如上所述,我想逐行读取“A.txt”,而不是完全读取到 memory,并与“B.txt”合并,然后再将其写出。

非常感谢你的帮助!

(使用示例文件更新原始帖子)

head A.txt
clusterID       kegg_contig     contig
Cluster_10700   Unassigned_ERR1801630_792963    ERR1801630_contig_792963
Cluster_10700   Unassigned_ERR1801633_537686    ERR1801633_contig_537686
Cluster_10700   Unassigned_ERR505054_53474      ERR505054_contig_53474
Cluster_10700   Unassigned_ERR505054_31574      ERR505054_contig_31574


head B.txt
contig  coverage
ERR1726751_contig_1     28.82716
ERR1726751_contig_2     12.265934
ERR1726751_contig_3     17.733767
 initDF = pd.read_csv("merge_a.csv", sep=",", header=0) 
 file2 = "merge_b.csv" 
 for chunks in pd.read_csv(file2, sep=",", chunksize=50, header=0): 
      print(chunks)
      initDF = initDF.merge(chunks, how='inner', on=['contig'])

 print(initDF)

对于这样一个简单的问题,很容易逐行处理一个文件,只要合并字段在另一个文件中是唯一的。 对于答案的其余部分,我将假设contig在 B.txt 中是唯一的:

import csv

# load B into a dictionary
with open('B.txt') as file_B:
    rd = csv.reader(file_B, delimiter='\t')
    _ = next(rd)             # skip header line
    dict_B = {row[0]: row[1] for row in rd}

# process file A line by line
with open('A.txt') as fdin, open('merged_file.txt', 'w', newline='') as fdout:
    rd = csv.reader(fdin, delimiter='\t')
    wr = csv.writer(fdout, delimiter='\t')
    # process header line
    row = next(rd)
    row.append('coverage')  # append last column header
    wr.writerow(row)
    # process data line
    for row in rd:
        row.append(dict_B[row[2]])  # append last field
        wr.writerow(row)

这只使用了csv模块,不使用pandas。 它将节省很多 memory,但可能需要更多时间...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM