Writing multiple lists to csv Python

前端 未结 2 370
故里飘歌
故里飘歌 2021-01-23 20:27

Im trying to write a function that writes multiple lists to a singular csv file and i am able to get the column titles to write, but not any of the data. My data is in lists tha

相关标签:
2条回答
  • 2021-01-23 21:07

    As the name implies, writerows writes rows, not columns. Furthermore, your lists are not equally sized, so you'll need to do something to account for that. The standard way of handling such a thing is using itertools.zip_longest.

    from itertools import zip_longest # izip_longest in python2.x
    
    with open("assignment_7_results.csv", "w") as f:
        w = csv.writer(f)
        w.writerow(["Number of Words", "Words/Sentence"])
        for x, y in zip_longest(number_of_words_sentence, mean_word_per_sentence):
            w.writerow([x, y])
    
    0 讨论(0)
  • 2021-01-23 21:10

    Try this to store the data in csv file with multiple list of different length. Here I tried to give header same as A and B as list name.

    import pandas as pd
    
    A = ['Apple', 'Dog']
    
    B = ['Cat', 'OWL', 'PEACOCK']
    
    dict_1 = {'A': A, 'B': B}
    
    df = pd.DataFrame.from_dict(dict_1, orient='index')
    
    dt = df.transpose()
    
    dt.to_csv('myfile.csv', index=False, header=True,  encoding='utf-8')
    
    0 讨论(0)
提交回复
热议问题