簡體   English   中英

將多個列表寫入 csv Python

[英]Writing multiple lists to csv Python

我正在嘗試編寫一個將多個列表寫入單個 csv 文件的函數,並且我能夠寫入列標題,但不能寫入任何數據。 我的數據在與此 [92,3801,2,22,4] 類似的列表中,第二個是 [3.0,2,23,5],我正在尋找有關此的指導。 謝謝!

import csv
def export_results(number_of_words_sentence,mean_word_per_sentence):
    with open("assignment_7_results.csv", "w", newline="") as Assignment_7_results:
        writer = csv.writer(Assignment_7_results)
        writer.writerow(["Number of Words", "Words/Sentence"])
    # Our .csv file will have two columns, one for the dict keys and one for the dict values
        writer.writerows(number_of_words_sentence)
        writer.writerows(mean_words_per_sentence)

顧名思義, writerows寫入行,而不是列。 此外,您的列表大小不同,因此您需要做一些事情來解決這個問題。 處理這種事情的標准方法是使用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])

嘗試將數據存儲在具有多個不同長度列表的 csv 文件中。 在這里,我嘗試將與 A 和 B 相同的標題作為列表名稱。

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM