python - 在方法结束时传入无限元组作为参数

标签 python pandas

我想创建一个可以在末尾接收任意数量元组的函数。

这在将多个数据框写入同一个 Excel 文件时非常有用,例如一份包含多个主题及其各自工作表规范的报告 (Science, 1, 1) (Math, 2, 1) (English, 3, 1 ).

对于这个例子,我有 def visualize(project_dir, report_name, df, sheet_name, header_row):

但我想让它像def visualize(project_dir, report_name, *(df, sheet_name, header_row)):

def visualize(project_dir, report_name, df, sheet_name, header_row):
    def template_path(project_path, report_name):
        return project_path + "\\" + report_name + " Template.xlsx"

    def timestamp():
        return datetime.now().strftime("%m-%d-%Y %I%M%p")

    def output_path(project_path, report_name):
        return project_path + "\\" + report_name + " Report " + timestamp() + ".xlsx"

    template_path = template_path(project_dir, report_name)
    output_path = output_path(project_dir, report_name)

    try:
        with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
            df.to_excel(writer, sheet_name=sheet_name, startrow=header_row, index=False,
                                           header=False)
        writer.save()

        paste_formatting(template_path, output_path, sheet_name)
    except:
        print("Formatting failed; reverting to raw data")
        with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
            df.to_excel(writer, sheet_name=sheet_name, index=False)
        writer.save()

最佳答案

您不能使用 *(df, sheet_name, header_row)。只需使用 *args 然后遍历它们。

def visualize(project_dir, report_name, *args):
    ...
    for df, sheet_name, header_row in args:
        ...

然后你可以这样调用它:

visualize("dirname", "report_name", (df1, "sheet1", ["col1", "col2"]), (df2, "sheet2", ["heading1", "heading2", "heading3"]), ...)

关于python - 在方法结束时传入无限元组作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57511633/

相关文章:

python - 为什么我无法关闭本体世界

python - 在 python 中处理任意大的数字

pandas - 时间增量错误;版本 0.15.1-=np19py27_0

python - 工作线程内的 Queue.put 失败

python - Pandas 无法使用聚合函数列表进行聚合

python - 从 itertools 组合列表结果中删除括号

python - 在 Python 中,如何以可读格式显示当前时间

postgresql - 如何处理 pandas 数据帧整数列中的 NaN 到 postgresql 数据库

python - 谷歌云机器学习引擎 "Skipping evaluation due to same checkpoint"

python - 从 csv 文件 python 解析字典