Search code examples
dataframepython-polars

How to select columns by data type in Polars?


In pandas we have the pandas.DataFrame.select_dtypes method that selects certain columns depending on the dtype. Is there a similar way to do such a thing in Polars?


Solution

  • One can pass a data type to pl.col:

    import polars as pl
    
    df = pl.DataFrame(
        {
            "id": [1, 2, 3],
            "name": ["John", "Jane", "Jake"],
            "else": [10.0, 20.0, 30.0],
        }
    )
    print(df.select([pl.col(pl.String), pl.col(pl.Int64)]))
    

    Output:

    shape: (3, 2)
    ┌──────┬─────┐
    │ name ┆ id  │
    │ ---  ┆ --- │
    │ str  ┆ i64 │
    ╞══════╪═════╡
    │ John ┆ 1   │
    │ Jane ┆ 2   │
    │ Jake ┆ 3   │
    └──────┴─────┘