pythonpython-polarspolars

Python Polars: How to add columns in one lazyframe to another lazyframe?


I have a Polars LazyFrame and would like to add to it columns from another LazyFrame. The two LazyFrames have the same number of rows and different columns.

I have tried the following, which doesn't work as with_columns expects an iterable.

def append_columns(df:pl.LazyFrame):
    df2 = pl.LazyFrame([1,2])
    return df.with_columns(df2)

Solution

  • For this, pl.concat setting how="horizontal" might be used.

    import polars as pl
    
    df = pl.LazyFrame({
        "a": [1, 2, 3],
        "b": [4, 5, 6],
    })
    
    other = pl.LazyFrame({
        "c": [9, 10, 11],
        "d": [12, 13, 14],
        "e": [15, 16, 17],
    })
    
    result = pl.concat((df, other.select("c", "d")), how="horizontal")
    

    The resulting pl.LazyFrame then looks as follows.

    shape: (3, 4)
    ┌─────┬─────┬─────┬─────┐
    │ a   ┆ b   ┆ c   ┆ d   │
    │ --- ┆ --- ┆ --- ┆ --- │
    │ i64 ┆ i64 ┆ i64 ┆ i64 │
    ╞═════╪═════╪═════╪═════╡
    │ 1   ┆ 4   ┆ 9   ┆ 12  │
    │ 2   ┆ 5   ┆ 10  ┆ 13  │
    │ 3   ┆ 6   ┆ 11  ┆ 14  │
    └─────┴─────┴─────┴─────┘