Apply on Dataframe 将第一行值传递给所有行

Apply on Dataframe passes first row values to all rows

当以下面的方式使用 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 名称格式的字典。 document 是一个 docx-python 对象。

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

这最终成为 loop/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")