2017-10-05 109 views
1

我有兩個CSV列文件數不同的csv文件。我想合併這些csv文件的第一列(他們有不同的列名)。合併具有不同列數和列名的兩個csv文件

CSV 1:

ID, name, A1, A2, A3 
1101,臺泥,29.19,2998730.0,0.23 
1102,亞泥,36.06,933069.0,0.08 
1103,嘉泥,23.29,132555.0,-0.17 
1104,環球水泥,25.64,139041.0,0.45 
1108,幸福水泥,11.8,80854.0,0.05 

CSV2:

NO, no_name, D1, D2, D3, D4 
01003T,兆豐新光R1,14.08,14.08,13.95,14.00 
01004T,土銀富邦R2,13.39,13.40,13.30,13.34 
01007T,兆豐國泰R2,14.76,14.76,14.76,14.76 
1101,臺泥,35.45,35.45,34.80,35.15 
1102,亞泥,26.45,26.50,26.30,26.50 
1103,嘉泥,8.71,8.71,8.61,8.71 

如果CSV2 NO = csv1 ID,追加D1,D2,D3,D4到csv1,新CSV是這樣的:

ID, name, A1, A2, A3, D1, D2, D3, D4 
1101,臺泥,29.19,2998730.0,0.23,35.45,35.45,34.80,35.15 
1102,亞泥,36.06,933069.0,0.08,26.45,26.50,26.30,26.50 
1103,嘉泥,23.29,132555.0,-0.17,8.71,8.71,8.61,8.71 

我的想法是:readlines爲兩個csv文件,比使用雙循環找出第一列的相同值,比結合第一個csv fil e和第二CSV文件中的某些列,比創建一個合併csv文件,下面是代碼:

`import csv 

# readlines for the two csv file 
inf = open('csv1.csv', "r").readlines() 
inf1 = open('csv2.csv', "r").readlines() 

data = {} 

# use double loop find out the same value of first column 
# combine first csv file and certain columns in second csv file 
for line in inf: 
    part = line.split(',') 
    a = part[0] 
    for line1 in inf1: 
     part1 = line1.split(',') 
     b = part1[0] 
     if a == b in data:  
      row = line + ',' + part1[2] + ',' + part1[3] + ',' + part1[4] + ',' + part1[5]  

# create a merge csv file   
with open('m_data.csv', 'w', newline = '') as f_out: 
    fieldnames = ['ID', 'name', 'A1', 'A2', 'A3', 'D1', 'D2', 'D3', 'D4'] 
    writer = csv.DictWriter(f_out, fieldnames = fieldnames) 

    writer.writeheader() 

for c1, c2, c3, c4, c5, c6, c7, c8, c9 in data.items(): 
    writer.writerow({'ID': c1, 'name': c2, 'A1': c3, 'A2': c4, 'A3': c5,'D1': c6, 'D2': c7, 'D3': c8, 'D4':c9}) 

f_out.close()` 

我想可能問題之間「相結合的第一個CSV文件和某些列在第二csv文件「和」創建一個合併CSV文件「,但我不知道如何解決它,或者有另一種方式?

非常感謝您的幫助!

+0

請從每個文件中添加幾行樣本輸入數據。僅供參考,請參閱如何發佈[mcve]。 –

回答

1

這個解決方案應該按預期工作:

import csv 
from collections import OrderedDict 


data = OrderedDict() 

with open('temp.csv', 'r', encoding='utf-8', newline='') as infile1: 
    reader1 = csv.reader(infile1) 
    next(reader1, None) # Skip header. 
    for row in reader1: 
     data[row[0]] = row # id as the key and row as the value. 

file2_NOs = set() # A set to store the NO fields of file2. 

with open('temp2.csv', 'r', encoding='utf-8', newline='') as infile2: 
    reader2 = csv.reader(infile2) 
    next(reader2, None) # Skip header. 
    for row in reader2: 
     file2_NOs.add(row[0]) # Add the NO fields to this set. 
     if row[0] in data: # If the NO/id exists in file1... 
      data[row[0]].extend(row[2:]) # ... extend the rows. 

with open('temp3.csv', 'w', encoding='utf-8', newline='') as outfile: 
    writer = csv.writer(outfile) 
    writer.writerow(['ID', 'name', 'A1', 'A2', 'A3', 'D1', 'D2', 'D3', 'D4']) 
    for row in data.values(): 
     if row[0] in file2_NOs: # Write only if the number/id exists in file 2. 
      writer.writerow(row) 

我先用ID作爲鍵和行的值文件1的行添加到OrderedDict。然後,我遍歷第二個文件,如果NO在字典中作爲關鍵字存在,我擴展該行。我還添加了一組(file2_NOs),我在其中添加了NO,這樣我就可以檢查ID是否也是有效的NO,然後只要在兩個文件中都存在ID和NO的情況下寫入行。

+0

你也可以看看這是否可以用[pandas](http://pandas.pydata.org/)更容易解決。 – skrx

+0

我已經刪除了'contextlib.ExitStack',因爲你也可以使用3''''語句。它工作正常嗎? – skrx

+0

對不起,我遲到了! –

相關問題