熊猫-合并无索引单元格

时间:2020-06-30 15:20:58

标签: python-3.x excel pandas dataframe

我在Pandas中具有带有多索引的数据框。

它的设置方式:

multi = pd.MultiIndex.from_frame(data)
data.set_index(multi, inplace=True)

现在,我使用合并的索引(将to_excelmerge_cells=True一起使用来将数据保存到excel):

Current result

我试图弄清楚如何将分割数据索引合并。

就像这里:

Expected Result

现在,我尝试将ExcelWriterengine='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
            }

0 个答案:

没有答案