加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 13:15:01 所属栏目:Python 来源:网络整理
导读:我正在尝试向csv文件中的数据添加新行.添加数据时,不会将其插入下一行,而是将其添加到上一行的末尾.我的问题代码目前看起来像: qlist = list(data)entries = [response,0]df = pd.DataFrame([entries],columns=qlist)df.to_csv('data.csv',index=False,head
我正在尝试向csv文件中的数据添加新行.添加数据时,不会将其插入下一行,而是将其添加到上一行的末尾.我的问题代码目前看起来像:

qlist = list(data)
entries = [response,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,4,5,6

但你想要的是这个:

col1,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,6

希望这可以帮助.如果没有,请告诉我,我会再看一遍.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读