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 data type(s) 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.Int64)))
    

    Output:

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