![](/img/trans.png)
[英]How can I insert data from a CSV file into a dataframe using pandas.read_csv?
[英]How to insert data from a appened list to the csv file using pandas?
我有一個從網站上抓取的預測數據,並以下面的形式應用了 ARIMA 算法
predicted=12891.806866, expected=12890.000000
predicted=12889.863342, expected=12890.000000
predicted=12880.874762, expected=12890.000000
.....
......
........
predicted=10453.575744, expected=10999.000000
predicted=10873.639037, expected=10999.000000
predicted=11021.455329, expected=10490.000000
predicted=10620.855937, expected=10490.000000
我通過以下片段獲得了這些數據
for t in range(len(test)):
model = arima_model.ARIMA(history, order=(10,1,0))
model_fit = model.fit(disp=0)
output = model_fit.forecast()
yhat = output[0]
predictions.append(yhat)
obs = test[t]
history.append(obs)
print("predicted=%f, expected=%f" % (yhat, obs))
print(predictions) #returns only single value [array([12755.95876035])]
print(history) #returns [15095, 14890, 14890, 14449, 14449, 14449, 14890, 14890, 14890, 14890, 14890, 14890, 14890, ....................................... ,12990, 12990, 12990, 12990, 12990]
當我嘗試將此數據添加到 csv 文件中的現有列時,我並沒有真正看到所有數據都填充在所有行中。 我嘗試了不同的已知技術。 但我失敗得很慘。 我意識到我沒有以正確的方式讀取/復制數據以插入 csv 文件。 我在下面編寫的技術是我嘗試過的簡單示例
1.
df = pd.read_csv("mydata.csv")
df['Predicted'] = yhat
df['Expected'] = obs
df.to_csv("mydata.csv")
2.
with open("mydata.csv", "w") as data:
w = csv.DictWriter(data, fieldnames={"Predicted", "Expected"})
w.writeheader()
w.writerow({'Predicted': yhat, 'Expected': obs})
#Even w.writerows didn't really help
3.
df.insert(value=yhat, column="Predicted", allow_duplicates = True)
RESULT:
Empty DataFrame
Columns: [Expected, Predicted]
Index: []
i ended up with column filled up with only one row from the above print("predicted=%f, expected=%f" % (yhat, obs))
我想用所有預測值和預期值填充 mydata.csv 。 我知道我在這里缺少一些技術。 如果有人幫助我,那就太好了。
提前致謝!
如果您的predictions
和history
是“附加列表”:
df = pd.read_csv("mydata.csv")
df['Predicted'] = predictions
df['Expected'] = history
df.to_csv("mydata.csv")
我有點高興回答我自己的問題。 在打開 csv 文件“with”后進行循環。
with open('mydata.csv', 'a+') as csvfile:
fieldnames = ['Expected', 'Predicted']
w = csv.DictWriter(csvfile, fieldnames=fieldnames)
w.writeheader()
for t in range(len(test)):
model = ARIMA(history, order=(10, 1, 0))
model_fit = model.fit()
output = model_fit.forecast()
yhat = output[0]
predictions.append(yhat)
obs = test[t]
history.append(obs)
print("predicted=%f, expected=%f" % (yhat, obs))
w.writerow({'Expected' : obs, 'Predicted' : yhat})
df_predicted = pd.read_csv("mydata.csv")
print(df_predicted)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.