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!

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

It is a csv file. I should have been more careful while giving a dummy example.
@Aisha In that case, you can remove the delimiter="\t" and sep="\t" named arguments.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.