首页 > 解决方案 > 迭代函数每次都会覆盖数据帧

问题描述

所以我将多个 docx 文件转换为数据框文件。该代码适用于一个文档,这导致以下结构:

data = {'Title': ['title first article, 'title second article'], 'Sources': ['source of first article', 'source of second article']}
df = pd.DataFrame(data=data)

该结构是一个函数的结果:

def func_convert_updates(filename):
    path = os.chdir('C:/Users/docxfiles')
    regex = '\xc2\xb7'
    with open(filename, "rb") as docx_file:
        result = mammoth.convert_to_html(docx_file)
        text = result.value # The raw text
        text2=re.sub(u'[|•●]', " ", text, count= 0) 
        with open('output.txt', 'w', encoding='utf-8') as text_file:
            text_file.write(text2)

    #followed by many lines of code, omitted here, to create a dataframe

    return df_titles

然后我想分析多个 docx 文件,因此我编写了以下代码:

list_news= ['docx_file_1', 'docx_file_2.docx', ... etc]

for element in list_news:
    df_titles = func_convert_updates(element)

但是,这仅返回列表最后一个元素的数据帧,因为它会覆盖先前的输出。我该如何解决这个问题?先感谢您。

标签: pythonpandasdataframe

解决方案


如果您想将在每个循环中创建的所有 DataFrames 都放在变量中,df_titles您可以执行以下操作:

import pandas as pd

df_titles = pd.concat([func_convert_updates(element) for element in list_news], ignore_index=True)

推荐阅读