0

Apologies in advance if the problem sounds too trivial but I could not find any solution on the forum.

I want to merge two csv files.

file1:
name age city
john 20   abc
jack 15   def
alice 25  ghk

file2:
hobby grade 
tyu    8
ghj    9
hjk    10

output file:

name  age city hobby grade 
john  20  abc  tyu    8
jack  15  def  ghj    9
alice 25  ghk  hjk    10

What is the best way to do this? Can we do this using pandas?

Appreciate any help.

Thanks!

Aisha
  • 91
  • 7
  • Possible duplicate of [Merging two CSV files using Python](https://stackoverflow.com/questions/16265831/merging-two-csv-files-using-python) – Green Cloak Guy Feb 26 '19 at 20:20

1 Answers1

1

I'm assuming based on your example data that you're dealing with tab delimiters, not commas.

I believe what you're trying to do is generally referred to as concatenation, whereas merging is a database-style join on columns or indexes. Perhaps that's why you were having difficulty searching for a solution.

You can easily accomplish what you want with pandas as in the following:

import pandas as pd

a = pd.read_csv("file1.csv", delimiter="\t")
b = pd.read_csv("file2.csv", delimiter="\t")

print(pd.concat([a, b], axis=1).to_csv(index=False, sep="\t"))

Result:

name    age     city    hobby   grade
john    20      abc     tyu     8
jack    15      def     ghj     9
alice   25      ghk     hjk     10
cody
  • 11,045
  • 3
  • 21
  • 36
  • It is a csv file. I should have been more careful while giving a dummy example. – Aisha Feb 26 '19 at 21:01
  • @Aisha In that case, you can remove the `delimiter="\t"` and `sep="\t"` named arguments. – cody Feb 26 '19 at 21:12
  • I needed the result in a csv file instead of printing it. So, I used below line instead of print. pd.concat([a, b], axis=1).to_csv('myfile.csv',index=False) Thanks so much for your help. – Aisha Feb 27 '19 at 21:56