[Python] Explode Function and Reshaping in one Step

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have:

    keys = ["panda1", "panda2", "panda3"]
    values = [["eats", "shoots"], ["shoots", "leaves"], ["eats", "leaves"]]
    df = pd.DataFrame({"keys": keys, "values": values})

    keys values
    0 panda1 [eats, shoots]
    1 panda2 [shoots, leaves]
    2 panda3 [eats, leaves]


    Then I exploded the values in the values col:

    df1 = df.explode(olumn = 'values')

    keys values
    0 panda1 eats
    0 panda1 shoots
    1 panda2 shoots
    1 panda2 leaves
    2 panda3 eats
    2 panda3 leaves


    My question is how to get this output directly please:

    panda1 panda2 panda3
    0 eats shoots eats
    1 shoots leaves leaves

    • Can I get this directly in one step from the original df before explode()? if not
    • Is there a chance I can do this in 1 step with the explode function or no please?

    Thank you all in advance :)

    Continue reading...

Compartilhe esta Página