比较两个CSV文件,更新第二个

时间:2017-09-15 12:44:16

标签: pandas csv

我必须使用csv文件:allitems和allitemsnew。

我正在尝试比较这两个文件。如果我在“allitems”中有新行,我想将这些行添加到第二个文件中,就像更新一样。

这是我的代码,但我不知道我是否采用了正确的方式:

# Read the file with latest update
dftemp = pd.read_csv('allitemsnew.csv', delimiter=',', header=None,engine='python', usecols=range(0, 7), error_bad_lines=False)

# Check if there is any change but only first column.
# Combine the two datas and append new data from originalfile
dfnew = dftemp.merge(df, how='outer')

# Delete dublicates because if I execute my programm without changes I get each time more and more duplicates
dfnew.drop_duplicates(subset=[0], inplace=True, keep=False)

# Intersection of both files because normally I append new rows from original file to the allitemsnew-file. 
# But if I delete rows from original file there are not also removed in the second file. Therefore intersection
dfwrite=df.merge(dfnew, how='inner')

dfwrite.to_csv("allitemsnew.csv", index=False, header=None)

我的解决方案有效,但我不知道这是不是最好的方法。

  1. 我想与csv文件进行比较

  2. 我想用第一个文件中的新行或删除行更新第二个文件 仅与第一列进行比较,因为像“df.update()”这样的函数会覆盖所有行

  3. 我想首先使用status-rows插入一个新列。但它最后只插入。我尝试了reindex-Function,但它不起作用

0 个答案:

没有答案