Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

python - 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.)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...