python - 迭代函数每次都会覆盖数据帧
问题描述
所以我将多个 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)
但是,这仅返回列表最后一个元素的数据帧,因为它会覆盖先前的输出。我该如何解决这个问题?先感谢您。
解决方案
如果您想将在每个循环中创建的所有 DataFrames 都放在变量中,df_titles
您可以执行以下操作:
import pandas as pd
df_titles = pd.concat([func_convert_updates(element) for element in list_news], ignore_index=True)
推荐阅读
- python - 考虑到每个项目可以有多个主题,如何将数据集中每个项目的主题转换为特征向量
- wordpress - 如何使用 Wordpress ENQUEUE 函数链接样式表
- python - Keras 函数式 API:将可变长度列表传递到嵌入层
- javascript - 创建一个自定义表单以使用 Stripe 接受信用卡
- mongodb - updateOne 不会捕获错误。如何捕捉错误?
- python - 未找到带有参数 '('',)' 的 'new_entry' 的反向操作。尝试了 1 种模式:['new_entry/(?P
[0-9]+)/$'] - powershell - 如何移动文件名未在一组文本文件中使用的文件?
- python - 如何从文件中获取所有正数的总和?
- perl - 删除多行文本块
- javascript - 由 create-react-app 创建的 React 页面不适用于 IE。babel 不是很好用吗?