18

Can anyone check for me what's wrong with my code. I want it merge two csv file into one csv file.

I hve tried to google and I still cant merge it, it will create new file but will show nothing inside. https://stackoverflow.com/a/16266144/7624469

a.csv

ID    User
A1    Fi
A2    Ki

b.csv

ID    User
A4    Fsdi
A5    Kisd

The output that I want will look like this

combined.csv

ID    User
A1    Fi
A2    Ki
A4    Fsdi
A5    Kisd

test.py

import pandas, sys
import pandas as pd


a = pd.read_csv("C:/JIRA Excel File/a.csv")
b = pd.read_csv("C:/JIRA Excel File/b.csv")

merged = a.merge(b, on='ID')

merged.to_csv('C:/JIRA Excel File/result.csv', index=False)
cs95
  • 379,657
  • 97
  • 704
  • 746
Fiqri Mfbw
  • 243
  • 2
  • 5
  • 12

2 Answers2

22

Using df.append:

out = df1.append(df2)
print(out)

   ID  User
0  A1    Fi
1  A2    Ki
0  A4  Fsdi
1  A5  Kisd

with open('C:/JIRA Excel File/result.csv', 'w', encoding='utf-8') as f:
    out.to_csv(f, index=False)
cs95
  • 379,657
  • 97
  • 704
  • 746
12

It is better to use pd.concat here to combine this frames, not merge:

merged = pd.concat([a,b])

Toy example with your data:

a = pd.DataFrame([['Fi'],['Ki']],columns=['User'], index=['A1','A2'],) #'ID')
b = pd.DataFrame([['Fi'],['Ki']],columns=['User'], index=['A4','A5'],) #'ID')
pd.concat([a,b])

Will output:

    User
A1  Fi
A2  Ki
A4  Fi
A5  Ki
Grigory
  • 679
  • 1
  • 4
  • 22
  • it will display this error UnicodeDecodeError: 'utf-8' codec can't decode byte 0x93 in position 53: invalid start byte – Fiqri Mfbw Sep 06 '17 at 08:03
  • 3
    The unicode error has nothing to do with your original question. Specify the correct encoding to [read_csv](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html). –  Sep 06 '17 at 08:10
  • What's the practical difference between your suggestion of `concat` vs `append` as suggested in the accepted answer? – BeeOnRope Mar 12 '19 at 20:05
  • `append` is depreciated. – JonSG Jan 31 '23 at 16:25