[Python] How to recycle list to build a new column?

Discussão em 'Python' iniciado por Stack, Janeiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    How can I create the type column recycling a two-elements list ["lat","lon"]?

    adresse coord type
    "place 1" 48.943837 lat
    "place 1" 2.387917 lon
    "place 2" 37.843837 lat
    "place 2" 6.387917 lon

    As it would be automatically done in R with d$type <- c("lat","lon")

    Reprex :

    d0 = pl.DataFrame(
    {
    "adresse": ["place 1", "place 2"],
    "coord": [[48.943837, 2.387917], [37.843837, 6.387917]],
    }
    )
    d1 = d0.explode("coord")


    What I tried:

    d1 = d1.with_columns(type=pl.Series(["1","2"]))
    # ShapeError: unable to add a column of length 2 to a DataFrame of height 4

    d1 = d1.join(pl.DataFrame({"id":["1", "2"]}), how="cross")
    # logically, 8 rows instead of 4

    Continue reading...

Compartilhe esta Página