[Python] Pandas: add multiple columns to a multiindex column dataframe

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

  1. Stack

    Stack Membro Participativo

    This question is an attempt to generalise the solution provided for the this question:

    Pandas: add a column to a multiindex column dataframe

    I need to produce a column for each column index.

    The solution provided by spencerlyon2 works when we want to add a single column:

    df['bar', 'three'] = [0, 1, 2]

    However I would like to generalise this operation for every first level column index.

    Source DF:

    In [1]: df
    Out[2]:
    first bar baz
    second one two one two
    A -1.089798 2.053026 0.470218 1.440740
    B 0.488875 0.428836 1.413451 -0.683677
    C -0.243064 -0.069446 -0.911166 0.478370


    Target DF below, requires that the three column is the addition of the one and two columns of its respective index.

    In [1]: df
    Out[2]:
    first bar baz
    second one two three one two three
    A -1.089798 2.053026 0.963228‬ 1.440740 -2.317647 -0.876907‬
    B 0.488875 0.428836 0.917711 -0.683677 0.345873 -0.337804‬
    C -0.243064 -0.069446 -0.312510 0.478370 0.266761 0.745131‬

    Continue reading...

Compartilhe esta Página