2017-10-05 2 views
1

다른 열 수를 가진 두 개의 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, D1은, D2는, D3, D4가 csv1에 추가 새로운 CSV 이렇게 csv1 ID이다 = 경우

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 

내 생각은 : 두 csv 파일에 대한 readlines은 첫 번째 열의 동일한 값을 찾아 두 번 루프를 사용하는 것보다 첫 번째 CSV 파일을 결합하는 것보다 전자 및 제 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와 값과 같은 행이있는 OrderedDict에 파일 1의 행을 추가합니다. 그런 다음 두 번째 파일을 반복하고 dict에 키가 존재하면 행을 확장합니다. 나 또한 NO을 추가하는 집합 (file2_NOs)을 추가 했으므로 ID가 유효한 NO인지 확인하고 두 파일에 ID와 NO가 있으면 행을 쓸 수 있습니다.

+0

[pandas] (http://pandas.pydata.org/)에서 쉽게 해결할 수 있는지 확인할 수도 있습니다. – skrx

+0

'contextlib.ExitStack'은 3 개의 'with'문도 사용할 수 있으므로 제거했습니다. 제대로 작동합니까? – skrx

+0

늦어서 죄송합니다! –

관련 문제