pythondataframepython-polars

How do you copy a dataframe in polars?


In polars, what is the way to make a copy of a dataframe? In pandas it would be:

df_copy = df.copy()

But what is the syntax for polars?


Solution

  • That would be clone :

    df = pl.DataFrame(
        {
            "a": [1, 2, 3, 4],
            "b": [0.5, 4, 10, 13],
            "c": [True, True, False, True],
        }
    )
    
    df_copy = df.clone() #cheap deepcopy/clone
    

    Output : ​

    print(df_copy)
    ​
    shape: (4, 3)
    ┌─────┬──────┬───────┐
    │ a   ┆ b    ┆ c     │
    │ --- ┆ ---  ┆ ---   │
    │ i64 ┆ f64  ┆ bool  │
    ╞═════╪══════╪═══════╡
    │ 1   ┆ 0.5  ┆ true  │
    │ 2   ┆ 4.0  ┆ true  │
    │ 3   ┆ 10.0 ┆ false │
    │ 4   ┆ 13.0 ┆ true  │
    └─────┴──────┴───────┘