Reputation: 25
I am trying to do a regression analysis and then save the result in a csv file.
Two questions:
regr.predict
from sklearn import linear_model
) is being printed in csv in a single cell? I am trying to print every prediction in a separate row one below another (in my case I have 418 results so should be 418 rows in same column).
prediction1=regr.predict(xtest)
with open('my_output_file.csv', 'w', newline='') as f:
fieldnames=['PassengerId','Survived']
writer = csv.DictWriter(f, fieldnames)
writer.writeheader()
for result in prediction1:
writer.writerow({'PassengerId':'test','Survived':prediction1})
Upvotes: 0
Views: 162
Reputation: 26657
You're iterating on the prediction1 with "result" but you write the whole prediction1 on every row:
for result in prediction1:
writer.writerow({'PassengerId':'test','Survived':result})
You are already doing that. You first define the columns and their order (fieldnames
) and then when you call writerow()
, you give it a dict with the value for each column and csv.DictWriter
puts them in the right order.
You could write:
for result in prediction1:
writer.writerow({'Survived':result, 'PassengerId':'test'})
And have the same exact result.
Upvotes: 1