1

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

df.apply(make_word_file, axis=1)

奇怪的是,在 document.save() 中创建的文件名是正确的。newname在 row['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 单词文件的邮件合并。 mapfields是正则表达式格式的字典:列名。document是一个 docx-python 对象。

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

1 回答 1

1

这最终成为一个循环/python-docx 问题,而不是熊猫问题。

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")
于 2019-05-14T16:57:36.420 回答