Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Two CSV files in Python

I have two csv files and I want to create a third csv from the a merge of the two. Here's how my files look:

Num | status
1213 | closed
4223 | open
2311 | open

and another file has this:

Num | code
1002 | 9822
1213 | 1891
4223 | 0011

So, here is my little code that I was trying to loop through but it does not print the output with the third column added matching the correct values.

def links():
    first = open('closed.csv')
    csv_file = csv.reader(first)

    second = open('links.csv')
    csv_file2 = csv.reader(second)

    for row in csv_file:  
        for secrow in csv_file2:                             
            if row[0] == secrow[0]:
                print row[0]+"," +row[1]+","+ secrow[0]
                time.sleep(1)

so what I want is something like:

Num | status | code
1213 | closed | 1891
4223 | open | 0011
2311 | open | blank no match

like image 602
Helen Neely Avatar asked Aug 03 '26 01:08

Helen Neely


1 Answers

If you decide to use pandas, you can do it in only five lines.

import pandas as pd

first = pd.read_csv('closed.csv')
second = pd.read_csv('links.csv')

merged = pd.merge(first, second, how='left', on='Num')
merged.to_csv('merged.csv', index=False)
like image 111
Zenadix Avatar answered Aug 04 '26 13:08

Zenadix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!