[英]How do I update a CSV file with pandas without adding duplicates
我正在嘗試從 web 中獲取一些數據,這需要一段時間。 萬一發生任何事情,我會定期將數據保存在 csv 文件中。
但是,它只是將 dataframe 的新副本附加到 CSV 文件中。 這意味着文件中有大量重復項。
df.to_csv('data.csv', mode='a', header=False)
是我用來保存進度的命令。
謝謝閱讀。
IIUC,您有一個 dataframe 到 append 隨着時間的推移,您想定期備份。
您可以嘗試多種方法:
df.to_csv('data.csv', header=False) # or header=True
# (i) First time write the complete dataframe
df.to_csv('data.csv', header=False) # or header=True
# (ii) store the length of the dataframe at that point
lines_written = len(df.index)
# More data is being added to the dataframe from the web
# (iii) append new lines to CSV file
df.iloc[lines_written:].to_csv('data.csv', mode='a', header=False)
# (iv) update the line counter
lines_written = len(df.index)
# repeat steps (iii) and (iv)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.