簡體   English   中英

如何逐行合並兩個csv文件

[英]How to merge two csv files line by line

我在Windows中使用python 3.0。

我有2個CSV文件

file1.csv

0, 10,12
0,11,12
1,15,12
2, 17,12

file2.csv

0, 2, 1
1,22, 1
3, 11, 1

output.csv

0, 10,12
0,11,12
0, 2, 1
1,15,12
1,22, 1
2, 17,12
3, 11, 1

我嘗試了以下代碼

a = pd.read_csv('file1.csv')
b = pd.read_csv('file2.csv')
c = pd.concat([a, b], join='outer')
c.to_csv("Output.csv", index = False)

但是我的輸出是

0, 10,12
0,11,12
1,15,12
2, 17,12
0, 2, 1
1,22, 1
3, 11, 1

請給我一些指導。 我是python的新手。

您可以使用大熊貓將它們串聯並排序:

df = pd.concat([a, b]).astype('str')

df = df.sort_values(list(df.columns))

df.to_csv('Output.csv', index=False)

這不會創建輸出文件,但是它演示了heapq.merge如何heapq.merge幫助:

from heapq import merge
inputs = [file(f) for f in ['file1.csv', 'file2.csv']]
for line in merge(*inputs):
    print line,

利用樣本數據可以產生

0, 10,12
0, 2, 1
0,11,12
1,15,12
1,22, 1
2, 17,12
3, 11, 1

但是,這與示例輸出的初始行順序不同:

0, 10,12
0,11,12
0, 2, 1

但我不確定如何產生此訂單。 樣品輸出線不出現由字符或數字列進行排序(在字段的數字排序大概放0, 2, 1第一)。

編輯:看來行是有序的,好像沒有空格。 下面的例子:

from heapq import merge
def reader(f):
    for line in file(f):
        yield line.replace(' ',''), line
inputs = [reader(f) for f in ['file1.csv', 'file2.csv']]
for pair in merge(*inputs):
    print pair[1],

生成此順序:

0, 10,12
0,11,12
0, 2, 1
1,15,12
1,22, 1
2, 17,12
3, 11, 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM