Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将循环的输出保存到CSV文件?_Python_Pandas_Csv - Fatal编程技术网

Python 如何将循环的输出保存到CSV文件?

Python 如何将循环的输出保存到CSV文件?,python,pandas,csv,Python,Pandas,Csv,我想将此循环的示例输出保存到CSV [(16.0, 'thermionic vacuum diode device'), (4.0, 'adjustable electrodes')] [(16.0, 'thermionic vacuum diode device'), (4.0, 'adjustable electrodes')] [(9.0, 'heat transfer device')] 此输出是从 def write_csv(): for index, row in df.i

我想将此循环的示例输出保存到CSV

[(16.0, 'thermionic vacuum diode device'), (4.0, 'adjustable electrodes')]
[(16.0, 'thermionic vacuum diode device'), (4.0, 'adjustable electrodes')]
[(9.0, 'heat transfer device')]
此输出是从

def write_csv():
    for index, row in df.iterrows():
        text = row
        r.extract_keywords_from_sentences(text)
        r.get_ranked_phrases()
        score = r.get_ranked_phrases_with_scores()
        new_df = pd.DataFrame({'col':score})
        new_df = df.append(df)
        #print(score)
    df.to_csv("test_score_2.csv")
调用def write_csv时,csv文件仅包含最后一行,但我希望将所有行保存到csv文件中


有什么建议吗?

您在每一步都会覆盖df

def write_csv():
    data = []
    for index, row in df.iterrows():
        text = row
        r.extract_keywords_from_sentences(text)
        r.get_ranked_phrases()
        score = r.get_ranked_phrases_with_scores()
        data.append({'col': score})

     df = pd.DataFrame(data)
     df.to_csv("test_score_2.csv")
如果首先有一个df变量,那么您的追加逻辑可能会起作用。但是,没有

记住,给变量赋值会清除它用来指向的任何对象。您正在将变量指定给内存中的新对象