[Python] Custom Shaping in pandas for Excel Output

Discussão em 'Python' iniciado por Stack, Abril 28, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dataset with world population (For clarity, countries are limmited to Brazil, Canada, Denmark):

    import pandas as pd

    world = pd.read_csv("../data/worldstats.csv")

    cond = world["country"].isin(["Brazil","Canada","Denmark"])
    world = world[cond]
    world = world.set_index(["year","country"]).sort_index().head(10)

    world


    [​IMG]

    I want to reshapa my dataframe so the output would look like this


    year 1960
    country Population GDP
    Brazil 72493585.0 1.516557e+10
    Canada 17909009.0 4.109345e+10
    Denmark 4579603.0 6.248947e+09
    year 1961
    country Population GDP
    Brazil 74706888.0 1.523685e+10
    Canada 18271000.0 4.076797e+10
    Denmark 4611687.0 6.933842e+09
    Year 1962
    country Population GDP
    Brazil 77007549.0 1.992629e+10
    Canada 18614000.0 4.197885e+10
    Denmark 4647727.0 7.812968e+09


    I've look into and tried functions such as stack(), transpose(), pivot() and pivot_table(), not I'm unable to come up with a code that will generate the output that I want.

    I can use loops to generate the output but I want to export my output to an Excel spreadsheet. What would be the best way to it?

    Thank you.

    Continue reading...

Compartilhe esta Página