![](/img/trans.png)
[英]python pandas new row attached to last one in csv when using to_csv in append mode
[英]How to force a new line when appending to a csv using python pandas .to_csv
附加到 csv 時,我的第一行從現有的最后一行而不是新行開始。
我一直在搜索 SO,但我只是找到了在追加模式下打開 csv 或在寫入 csv 時使用追加模式的基本用法。 我無法理解這里接受的答案( to_csv 追加模式不追加到下一個新行),因為它似乎要求在使用f.write("/n")
") 寫入 ("/n") 之前打開現有文件f.write("/n")
。 這個答案( How to add pandas data to an existing csv file? )是最相關的,但我希望在一個函數中寫入多個數據框,所以我不想繼續打開它們。 我的計划是使用如下函數:
import os
def mysave(df,dfpath):
# if file does not exist write header
if not os.path.isfile(dfpath):
df.to_csv(dfpath, index = False)
else: # else it exists so append without writing the header
df.to_csv(dfpath, mode = 'a', index = False, header = False)
mysave(mydf, 'foo.csv')
我創建了一個非常簡單的示例,其中 foo.csv 的結構如下:
a b c d
5 1 ah doo
6 2 bah poo
7 2 dah coo
當我使用我的函數或這個簡單的代碼時:
import pandas as pd
df = pd.read_csv('foo.csv', index_col=False)
mydf = df
mydf.to_csv('foo.csv', mode='a', index = False, header = False)
這就是 foo.csv 最終的結果:
a b c d
5 1 ah doo
6 2 bah poo
7 2 dah coo5 1 ah doo
6 2 bah poo
7 2 dah coo
當我嘗試添加回車符作為標題時,例如mydf.to_csv('foo.csv', mode='a', index = False, header = ("/n"))
pandas(正確地)忽略了我的錯誤header 注釋並使用header = True
的默認值。
a b c d
5 1 ah doo
6 2 bah poo
7 2 dah cooa b c d
6 2 bah poo
7 2 dah coo
我有一個類似的問題,經過一番搜索,我沒有找到任何簡單/優雅的解決方案。 對我有用的最小修復是:
import pandas as pd
with open('foo.csv') as f:
f.write('\n')
mydf.to_csv('foo.csv', index = False, header = False, mode='a')
我假設您要將兩個數據幀中的另一個附加到單個數據幀中。
使用下面提到的命令將其作為單個命令
ans = pd.concat([df, df])
然后您可以將輸出轉換為 .csv 文件
如果您的數據框變得很大並且您想避免串聯,則可以使用
import csv
with open('foo.csv','ab') as out:
writer=csv.writer(out)
writer.writerow(())
在函數中或作為代碼中的片段。 如果您不在 Windows 上,也許您可以避免在 open 中添加 'b' 並僅使用 'a' (追加)打開文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.