在附加模式下使用to_csv时,python会将新行附加到csv中的最后一行

在附加模式下使用to_csv时,python会将新行附加到csv中的最后一行,python,csv,pandas,dataframe,Python,Csv,Pandas,Dataframe,我正在尝试向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”变量将与最后一行的最后一个数据值

我正在尝试向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
# 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)
您的代码生成一些新数据:

#New Data
5,6 
当试图将其附加到旧数据中时,最终会得到以下结果

col1,col2
1,3
2,4,5,6
但你想要的是:

col1,col2
1,3
2,4
5,6
如果这是正确的,您应该将现有数据加载到pandas数据框中,将数据附加到该数据框中,然后覆盖旧的csv文件或生成新的csv文件

如果您有一个包含上述旧数据的csv文件,您可以这样做:

# Old data
col1,col2
1,3
2,4
# 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
希望这有帮助。如果没有,请告诉我,我会再看一遍。

哪些对象是数据和响应,它们的结构是什么(即嵌套列表、字典)?