python - 在 Dataframe 上应用将第一行值传递给所有行

标签 python python-3.x pandas python-docx pandas-apply

当以下面的方式使用 apply 时,作为“row”传递的值仅是来自数据帧第一行的值。

df.apply(make_word_file, axis=1)

奇怪的是,在 document.save() 中创建的文件名是正确的。 newname 在行['case_name'] 中具有正确的值。但是,如果我 print(row) 它会打印第一行的值。

def make_word_file(row):
    for key, value in mapfields.items():
#         print(row)
        regex1 = re.compile(key)
        replace1 = str(row[value])
        docx_replace_regex(document, regex1 , replace1)

    newname = remove(row['case_name'], '\/:*?"<>|,.')
    print(newname)
    document.save(datadir + row["datename"] + "_" + row["court"] + "_" + newname + ".docx")

我希望 print(row) 打印数据框中每一行的值,而不仅仅是第一行。

编辑清楚:

此脚本是一个邮件合并,可生成 .docx Word 文件。 mapfields 是一个 regex:column name 格式的字典。 document 是一个 docx-python 对象。

mapfields = {
"VARfname": "First Name",
"VARlname": "Last Name",
}

最佳答案

这最终是一个循环/python-docx 问题,而不是 pandas 问题。

document 对象被覆盖,在第一个对象之后,正则表达式找不到任何内容。在函数中加载文档模板解决了该问题。

def make_word_file(case_row):
    document_template = Document(directory + fname)
    document = document_template
    for key, value in mapfields.items():
        regex1 = re.compile(key)
        replace1 = str(case_row[value])
        docx_replace_regex(document, regex1 , replace1)

    document.save(location + ".docx")

关于python - 在 Dataframe 上应用将第一行值传递给所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56133232/

相关文章:

Python替换文件中的特定数字而不更改其他数字

python - 如何使用 Python 将 Pandas DataFrame 导出到 Google 表格?

python-3.x - Numpy 具有复数和 +=

pandas - 将 Int64Index 转换为 Int

Python 格式和 Pandas

python - Tensorflow 序列扩展的动态 __len__?

python - python进程之间的共享内存

python - 使用qcachegrind处理profilestats输出时如何源注释python

python-3.x - 如何避免Pygame用旋转球使新的Mac Pro崩溃

python - WSGI无法导入本地安装的包