我想创建一个可以在末尾接收任意数量元组的函数。
这在将多个数据框写入同一个 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/