簡體   English   中英

將新的 csv 數據與主數據進行比較,並從新的 csv 中刪除重復項並從文件中獲取清理過的 csv 數據

[英]compare a new csv data with master data and remove duplicates from the new csv and get cleaned csv data from the file

我有一個包含兩列的主文件,其中包含來自所有舊記錄的數據。 每當我得到一個包含兩列的新數據文件時,我想將它與主文件進行比較,並從新文件中刪除重復值,並從新數據中獲取清理過的數據,而無需更改主文件中的任何內容。

np.setdiff1d(new_file, master_file)

我已經嘗試了上面的代碼,但沒有給出想要的結果

這是一個非常快速的修復解決方案,它對文件中的更改不是很健壯,並且有一些迭代。 但是如果它是相對較小的文件並且是一次性的,這很有效。

test_master = pd.read_csv('data/test_master.csv')
test_new = pd.read_csv('data/test_new.csv')

drop_these = []

for i,d in enumerate(zip(test_new.iloc[:,0], test_new.iloc[:,1])):
    if d in zip(test_master.iloc[:,0], test_master.iloc[:,1]):
        drop_these.append(i)
        
test_new.drop(drop_these, inplace=True)

另外,如果您不想使用熊貓,則不是最佳解決方案:

import csv

master_file = []
with open("data/test_master.csv", "r") as f:
    writer = csv.reader(f)
    for row in writer:
        master_file.append(row)

new_file = []
with open("data/test_new.csv", "r") as f:
    writer = csv.reader(f)
    for row in writer:
        if row not in master_file:
            new_file.append(row)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM