我在Pandas中具有带有多索引的数据框。
它的设置方式:
multi = pd.MultiIndex.from_frame(data)
data.set_index(multi, inplace=True)
现在,我使用合并的索引(将to_excel
与merge_cells=True
一起使用来将数据保存到excel):
我试图弄清楚如何将分割数据与索引合并。
就像这里:
现在,我尝试将ExcelWriter
与engine='openpyxl'
一起使用,并通过 openpyxl 功能合并单元格,但是以某种方式在多索引数据框中选择范围会使脚本混乱。
合并范围变得疯狂(对于真实数据)。
值在1到5的范围内移动。
有“最稳定的”脚本版本之一:
def select_merged_cells(data: pd.DataFrame, columns: list) -> list:
# I know it's not most elegant solution but its probably best for readability.
def rows():
# Select rows by data length.
start_row = 2
for df_name, temp_df in data.groupby(level=0):
end_row = start_row + len(temp_df.values)
yield start_row, end_row
start_row = end_row+1
for start_row, end_row in rows():
for name in (el for el in columns if el in data.columns):
start_column = data.columns.get_loc(name) + 1 # Solution should be for more than one column to merge.
end_column = start_column
yield { # Expected by openpyxl `merge_cells` function.
"start_column": start_column,
"end_column": end_column,
"start_row": start_row,
"end_row": end_row
}