为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 python 的 pandas 和 numpy 库自动将数据存储在新行中

如何使用 python 的 pandas 和 numpy 库自动将数据存储在新行中

肥皂起泡泡 2023-03-16 16:04:21
我想将数据存储在 CSV 文件的第二行。但它每次都会覆盖第一行。怎么做?我使用循环在第二行存储数据。但它没有发生。我有什么想念的吗?  import pandas as pd    import numpy as np    a=1    def table_driven_agent(percept):        location=['A','B']        status=['clean','dirty']        percepts=[]        table=[location,status]        percepts.append(percept)        action = tableDrivenVaccum(percept,table)        if action == 'dirty':          action = dirty(percept[1])        return(action)    def tableDrivenVaccum(percept,table):        for i in table:            if i[0] == percept[0]:                return(i[1])    def dirty(percept):        if percept == 'A':            return('Go to B')        elif percept =='B':            return('Go to A')    while( a<10):        percept = list(map(str,input("Enter the status and position:").split(',')))        action = table_driven_agent(percept)        print(action)        dict = {'action': action, 'percept': percept}        df= pd.DataFrame(dict)         df.to_csv(r'index.csv', index =False, header=True)        a=1
查看完整描述

2 回答

?
喵喔喔

TA贡献1735条经验 获得超5个赞

写入 csv 会创建一个新的 csv 并替换当前的 csv。这就是它写入第一行的原因:它实际上删除了前一行并写入空白文件。

您正在寻找的是附加df到当前 csv 中。这可以通过以下方式完成:

df.to_csv('index.csv', index=False, mode='a', header=True)

注意我添加了mode='a'。这意味着模式=追加。默认mode'w', 表示“写入”(覆盖)。

这种方式df被添加到当前 csv 的最后一行。

如果您的 csv 有超过 2 行并且您只想更改第二行,您应该首先将所有 csv 加载到数据框。然后你可以只更改第二行 ( df.loc[1,:]=...) 然后将它全部保存到 csv ( df.to_csv(r'index.csv', index =False, header=True)


查看完整回答
反对 回复 2023-03-16
?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

好的,我自己解决了这个问题,方法是读取旧的 CSV 文件并将其合并并放入 CSV 文件中。你必须像我一样创建 CSV 文件 index.csv。然后将列名作为百分比和操作来工作。如果您的代码位置中没有 CSV 文件,将会出错。它会自动合并 CSV 文件中的最新输入而不删除任何行。

注意:index.csv、百分比和操作只是一个示例。你也可以使用你的。


import pandas as pd

import numpy as np

i = 1

def table_driven_agent(percept):

    location=['A','B']

    status=['clean','dirty']

    percepts=[]

    table=[location,status]

    percepts.append(percept)

    action = tableDrivenVaccum(percept,table)

    if action == 'dirty':

      action = dirty(percept[1])

    return(action)

def tableDrivenVaccum(percept,table):

    for i in table:

        if i[0] == percept[0]:

            return(i[1])

def dirty(percept):

    if percept == 'A':

        return('Go to B')

    elif percept =='B':

        return('Go to A')

while i < 6:        

    percept = list(map(str,input("Enter the status and position:").split(',')))

    action = table_driven_agent(percept)

    print(action)

    

    df_old =pd.read_csv('index.csv')

    newData=[[percept,action]]

    colNames =df_old.columns


    df_new = pd.DataFrame(data=newData, columns=colNames)

    df_complete = pd.concat([df_old,df_new],axis=0)

    df_complete.to_csv('index.csv',index=False)

    

    #dict = {'percept': percept, 'action': action}

    #df= pd.DataFrame(dict) 

    #df.to_csv(r'index.csv', index =False, header=True,mode='a')

    i =1

//img1.sycdn.imooc.com//6412cdbd0001724a06390397.jpg

查看完整回答
反对 回复 2023-03-16
  • 2 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信