Kavikayal
Kavikayal

Reputation: 143

Joining 2 csv files in python based on index values

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

Upvotes: 0

Views: 1520

Answers (1)

Alex
Alex

Reputation: 7045

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.

Upvotes: 3

Related Questions