根据索引值在python中加入2个csv文件

时间:2018-12-18 14:23:57

标签: python

在python中,我想基于索引值连接/合并2个csv文件。两个文件都有索引列,并且基于索引,我们必须将一个csv的特定列添加到另一个csv。

例如: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..

输出csv:

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

请帮我用Python编写代码

1 个答案:

答案 0 :(得分:1)

这是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)

您可以阅读有关opening your files heremerging here的更多信息。