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
)

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
添加回答
舉報