Elmar
Elmar

Reputation: 25

CSV writer print the list in one cell

I am trying to do a regression analysis and then save the result in a csv file.

Two questions:

  1. Why set/list of results coming from regression analysis (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})
    
  2. How do I make python write in a certain column or even in a certain cell in csv? (For example, if I want to have a passenger ID in the first column and then have regression results in second column.)

Upvotes: 0

Views: 162

Answers (1)

Eric Darchis
Eric Darchis

Reputation: 26657

  1. 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})
    
  2. 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

Related Questions