![](/img/trans.png)
[英]How to force a new line when appending to a csv using python pandas .to_csv
[英]python pandas new row attached to last one in csv when using to_csv in append mode
我正在嘗試向csv文件中的數據添加新行。 添加數據時,不會將其插入下一行,而是將其添加到上一行的末尾。 我的問題代碼目前看起來像:
qlist = list(data)
entries = [response, 0,0,0,0]
df = pd.DataFrame([entries], columns=qlist)
df.to_csv('data.csv', index=False, header=False, mode='a')
運行此操作時,'response'變量最終與最后一行的最后一個數據值位於同一位置。 如何將條目添加到新行?
雖然你的代碼片段沒有多大意義,但我認為你的問題很有意思。 如果我正確理解你,你有(1)現有的csv文件,以及(2)你想要添加到該csv文件的代碼片段的一些輸出。 但是您的新數據將添加到現有csv文件的最后一行,而不是新行。
所以你開始的是這樣的:
# Old data
col1,col2
1,3
2,4
您的代碼會生成一些新數據:
#New Data
5,6
在嘗試將其附加到舊數據時,您最終會得到這個
col1,col2
1,3
2,4,5,6
但你想要的是這個:
col1,col2
1,3
2,4
5,6
如果這是正確的,您應該將現有數據加載到pandas數據框中,將數據附加到那里,然后覆蓋舊的csv文件或生成新文件。
如果你有一個帶有上述舊數據的csv文件,你可以這樣做:
# imports
import pandas as pd
# read existing data
df_old = pd.read_csv('C:/old.csv')
# Assign new data to a list.
# Note that the new data is written up as
# a list in the first element of a another list.
# Hence the double brackets.
# This way, the data is added as a row.
# If you use single brackets, pandas interprets
# the data as a column when added to a dataframe.
newData = [[5,6]]
# get column names of your existing data
colNames = df_old.columns
# make dataframe of new data that can be
# easily appended to your old data
df_new = pd.DataFrame(data=newData, columns=colNames)
# concatenate old and new
df_complete = pd.concat([df_old, df_new], axis = 0)
# write your complete dataset to a new csv.
df_complete.to_csv('data_new.csv', index=False)
現在你應該在csv文件中得到完整的數據集,如下所示:
col1,col2
1,3
2,4
5,6
希望這可以幫助。 如果沒有,請告訴我,我會再看一遍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.