[Python] Can I re-order column headers/rows in a multi-index pandas pivot table to have the...

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm creating a pivot table in pandas and exporting it to an excel file. I would like to re-organize the headers/rows to essentially have the valuefields header be in between the 2 columnfields headers.

    Current Excel View:

    [​IMG]

    Desired Excel View:

    [​IMG]

    My current snip of code is below. I've tried a variety of swaplevels, sort_index, and stack functions without luck. Maybe converting the pivot to a dataframe and then just swapping rows 2 and 3 would work? I just don't know how to do that.

    indexfields = ['GEO DIMENSION', 'CLIENT DIMENSION']
    columnfields = ['CBRAND DIMENSION', 'TGTTYPE DIMENSION']
    valuefields = ['1H24R', '2H24R', '1H_TARGET', '2H_TARGET']

    piv_df = pd.pivot_table(
    piv_df,
    index=indexfields,
    columns=columnfields,
    values=valuefields,
    fill_value=0,
    aggfunc="sum"
    ).reset_index()

    piv_df = piv_df.T.reset_index().T

    Continue reading...

Compartilhe esta Página