Merge Two Tables (csv) If (table1 Column A == Table2 Column A)
I have two CSV's, openable in Numbers or Excel, structured: | word | num1 | and | word | num2 | if the two words are equal (like they're both 'hi' and 'hi') I want it to become: |
Solution 1:
For csv
, I always reach for the data analysis library pandas
. http://pandas.pydata.org/
import pandas as pd
df1 = pd.read_csv('file1.csv', names=['word','num1'])
df2 = pd.read_csv('file2.csv', names=['word','num2'])
df3 = pd.merge(df1, df2, on='word')
df3.to_csv('merged_data.csv')
Solution 2:
Use a dict:
withopen('file1.csv', 'rb') as file_a, open('file2.csv', 'rb') as file_b:
data_a = csv.reader(file_a)
data_b = dict(csv.reader(file_b)) # <-- dictwithopen('out.csv', 'wb') as file_out:
csv_out = csv.writer(file_out)
for word, num_a in data_a:
csv_out.writerow([word, num_a, data_b.get(word, '')]) # <-- edit
(untested)
Solution 3:
I think what you're looking for is zip
, to let you iterate the two CSVs in lock-step:
withopen('file1.csv', 'rb') as f1, open('file2.csv', 'rb') as f2:
r1, r2 = csv.reader(f1), csv.reader(f2)
withopen('out.csv', 'wb') as fout:
w = csv.writer(fout)
for row1, row2 inzip(r1, r2):
if row1[0] == row2[0]:
w.writerow([row1[0], row1[1], row2[1]])
I'm not sure what you wanted to happen if they're not equal. Maybe insert both rows, like this?
else:
w.writerow([row1[0], row1[1], ''])
w.writerow([row2[0], '', row2[1]])
Post a Comment for "Merge Two Tables (csv) If (table1 Column A == Table2 Column A)"