繁体   English   中英

在追加模式下使用to_csv时,python pandas新行附加到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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM