class 中数据帧的数据 classes

Dataclasses for dataframes in the class

我有一个结果 class,我在其中计算了许多数据帧(大约 30 个)并将它们分配给 class.

的属性
class Result:
    def __init__(self, df1)
      self.df1=df1

我想在指定位置将数据帧写入 excel。为此我有一个函数

append_df_to_excel(df, sheet_name='Sheet1', startrow=0, startcol=0)

它以数据帧、sheet_name 和 startrow 和 startcolumn 作为参数。

我现在正在做的是在函数 main 中有一个字典,我遍历它以在 excel:

中的指定位置写入数据帧
if __name__ == "__main__":
      result=Result(df)
      dic_to_excel = {5:result.df1}
      for start_col, df in dic_to_excel.items():
          append_df_to_excel(df, sheet_name="CORE", startrow=2, startcol=start_col)

我想知道使用数据 class 代替字典 dic_to_excel 是否合适,我在 excel 中给出了数据帧的位置。在 dataclass 中,我想我可以有一个数据框, sheet_name , startrow 和 startcol 作为属性。我可以为此使用 dataclasses 吗?

当然可以:

from dataclasses import dataclass

@dataclass
class Result:
    df: pd.DataFrame
    start_row: int
    start_col: int
    sheet_name: str

if __name__ == "__main__":
    results = [
        Result(df, sheet_name="CORE", start_row=2, start_col=5),
        # and so on
    ]
    for result in results:
        append_df_to_excel(result.df, sheet_name=result.sheet_name, startrow=result.start_row, startcol=result.start_col)