[Python] How to outer join/merge two frames with polars while updating left with right values?

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

  1. Stack

    Stack Membro Participativo

    So I got two csv which I load as polars frames:

    left:

    track_name,type,yield,group
    8CEB45v1,corn,0.146957,A
    A188v2,corn,0.86308,A
    B73v6,corn,0.326076,A
    CI6621v1,sweetcorn,0.0357792,A
    CML103v1,sweetcorn,0.510464,A


    right:

    track_name,type,yield,group
    8CEB45v1,corn,0.999,A
    B1234,pepper,1,B
    B1235,pepper,2,B


    my code so far:

    import polars as pl

    left = pl.read_csv("left.csv")
    right = pl.read_csv("right.csv")

    matching_columns = list(set(left.columns) & set(right.columns)) # I do this since I want to join sometimes frame which does not have a 100 % column match. In that case I want to simply add the new columns to the outer frame.

    outer = left.join(
    right,
    on=matching_columns,
    how="outer",
    coalesce=True,
    maintain_order="left",
    )
    outer


    my result:

    shape: (8, 4)
    ┌────────────┬───────────┬───────────┬───────┐
    │ track_name ┆ type ┆ yield ┆ group │
    │ --- ┆ --- ┆ --- ┆ --- │
    │ str ┆ str ┆ f64 ┆ str │
    ╞════════════╪═══════════╪═══════════╪═══════╡
    │ 8CEB45v1 ┆ corn ┆ 0.146957 ┆ A │
    │ A188v2 ┆ corn ┆ 0.86308 ┆ A │
    │ B73v6 ┆ corn ┆ 0.326076 ┆ A │
    │ CI6621v1 ┆ sweetcorn ┆ 0.0357792 ┆ A │
    │ CML103v1 ┆ sweetcorn ┆ 0.510464 ┆ A │
    │ B1234 ┆ pepper ┆ 1.0 ┆ B │
    │ B1235 ┆ pepper ┆ 2.0 ┆ B │
    │ 8CEB45v1 ┆ corn ┆ 0.999 ┆ A │
    └────────────┴───────────┴───────────┴───────┘


    my desired output: (yield of 8CEB45v1 from right updates value of left)

    shape: (7, 4)
    ┌────────────┬───────────┬───────────┬───────┐
    │ track_name ┆ type ┆ yield ┆ group │
    │ --- ┆ --- ┆ --- ┆ --- │
    │ str ┆ str ┆ f64 ┆ str │
    ╞════════════╪═══════════╪═══════════╪═══════╡
    │ 8CEB45v1 ┆ corn ┆ 0.999 ┆ A │
    │ A188v2 ┆ corn ┆ 0.86308 ┆ A │
    │ B73v6 ┆ corn ┆ 0.326076 ┆ A │
    │ CI6621v1 ┆ sweetcorn ┆ 0.0357792 ┆ A │
    │ CML103v1 ┆ sweetcorn ┆ 0.510464 ┆ A │
    │ B1234 ┆ pepper ┆ 1.0 ┆ B │
    │ B1235 ┆ pepper ┆ 2.0 ┆ B │
    └────────────┴───────────┴───────────┴───────┘

    Continue reading...

Compartilhe esta Página