0

In python, I want to join / merge 2 csv files based on index values.Both the files have index column and based on the index we have to add a particular column from one csv to another csv.

Ex: csv 1:

Index   topic   subject
1115    fcfs       Operating System
1923    dml        Database Management System
835     jdbc       Object_oriented_programing
1866    joints     Database Management System

CSV 2:

Index  Questions
180    When an object is seen from front..
1115   Case in which fcfs is the best algo
959    How does the scheduler know the time..

Output csv:

Index topic Subject           Questions
1115   fcfs Operating System  Case in which..

Pleas help me to write a code in Python

1
  • CSV 1 has 20 rows and CSV 2 has 500 rows .. I want to map all 500 rows in CSV 2 with CSV 1 values..Is it possible Commented Dec 19, 2018 at 13:48

1 Answer 1

3

This is an ideal use-case for pandas

import pandas as pd


csv_1 = pd.read_csv('csv1.csv')
csv_2 = pd.read_csv('csv2.csv')

merged = csv_1.merge(csv_2, on='Index')
merged.to_csv('output.csv', sep=',', header=True, index=False)

You can read more about opening your files here and merging here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer.. But CSV 1 has 20 rows CSV2 has 500 rows. Can I map all 500 to CSV 1 which has only 20 rows.
It would depend on what's in the CSV files. If there is no matching index in CSV1 then these rows will not match in the example. You could use the option how='outer' on the merge operation, but this would likely result in half filled rows.

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.