上下文

我从db中查询了一些数据为pd.dataframe,并在xlsx.writer引擎中将其与pd.ExcelWriter一起保存到格式化的xlsx模板中. 然后,保存的数据在另一个工作表中被动态公式和其他公式引用.

问题

In the excel, there are two sheets : "Raw Data" and "Format Data":
"Raw Data" Stores the fetched data, "Format Data" contains the formula and reference cells from "Raw Data"

After the ExcelWriter processed the excel file, the dynamic formula in "Processed Data" changed to array formula, which denied the formula to expand. For example, there is a formula:
=FILTER(UNIQUE('Raw Data'!$I$4:$I$2000),UNIQUE('Raw Data'!$I$4:$I$2000)<>0)
which should return all unique data from I4:I2000.

然而,Excel在ExcelWriter过程中将动态公式更改为I4:I400范围内的数组公式,因为原始模板只有396个唯一值.即使更新后的数据源具有超过396个唯一值,它也只能显示396个项目.

如果有人能好心地建议这个问题的原因,并提供一个解决方案来停止动态公式的变化,那就太好了.

Remarks: I am trying not to do the data processing with python so please don't comment on that.

代码嗅探FYR

writer = pd.ExcelWriter(excel_path, engine='openpyxl', mode='a', if_sheet_exists="overlay",)
    for config in excelUpdateConfigs:
        result = fetchSQL(db_conn, config["sql"])
        result = result.astype(config["dtype"])
        result.to_excel(writer, sheet_name="Raw Data", float_format="%.5f", startrow=2, startcol=config["startcol"], header=True, index=False, engine="io.excel.xlsx.writer")
writer.close()

我已经try

I have tried to do some research online but I can't see any related articles about dynamic formula right now.
I doubt that the low level logic of ExcelWriter is creating a new excel file based on the given path instead of editing on top of it so it breaks some of the equations and inserted items. Please advise if I'm wrong.

推荐答案

我试图用下面的代码重现你的问题:

import pandas as pd
import numpy as np

excel_path = 'test.xlsx'

data = np.random.uniform(low=-10, high=10, size=400)

result = pd.DataFrame(data, columns=['close'])

writer = pd.ExcelWriter(excel_path, engine='openpyxl', mode='a', if_sheet_exists="overlay",)
result.to_excel(writer, sheet_name="Raw Data", float_format="%.5f", startrow=2, startcol=8, header=True, index=False, engine="io.excel.xlsx.writer")
writer.close()

test.xlsx有两个选项卡:"原始数据","格式数据". 在格式数据单元格A1中,I输入以下内容

=FILTER(UNIQUE('Raw Data'!$I$4:$I$2000),UNIQUE('Raw Data'!$I$4:$I$2000)<>0)

After running the code, I saw filter function changed to this: enter image description here

所以我决定首先改变FILTER在"格式化数据"工作表中的应用方式,即在"格式化数据"中 Select A1:A2000,在公式栏中输入=FILTER(UNIQUE('Raw Data'!$I$4:$I$2000),UNIQUE('Raw Data'!$I$4:$I$2000)<>0),按Ctrl + Shift + Enter键.

这样openpyxl就不会改变它了,它总是可以容纳2000个数据点.

Python相关问答推荐

将整组数组拆分为最小值与最大值之和的子数组

为什么tkinter框架没有被隐藏?

沿着数组中的轴计算真实条目

PMMLPipeline._ fit()需要2到3个位置参数,但给出了4个位置参数

计算组中唯一值的数量

在np数组上实现无重叠的二维滑动窗口

SQLAlchemy Like ALL ORM analog

Python避免mypy在相互引用中从另一个类重定义类时失败

交替字符串位置的正则表达式

干燥化与列姆化的比较

比Pandas 更好的 Select

用fft计算指数复和代替求和来模拟衍射?

如何获取包含`try`外部堆栈的`__traceback__`属性的异常

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上

如何从数据框列中提取特定部分并将该值填充到其他列中?

替换包含Python DataFrame中的值的<;

多索引数据帧到标准索引DF

是否将Pandas 数据帧标题/标题以纯文本格式转换为字符串输出?

关于数字S种子序列内部工作原理的困惑

正则表达式反向查找