Search code examples
pythonpython-3.xpython-polars

How to select last column of polars dataframe


I have the following polars dataframe and I wanted to select the last column dynamically.

>>> import polars as pl
>>> 
>>> df = pl.DataFrame({
...     "col1": [1, 2],
...     "col2": ["2", "3"],
...     "col3": [3, 4]
... })
>>> 
>>> df
shape: (2, 3)
┌──────┬──────┬──────┐
│ col1 ┆ col2 ┆ col3 │
│ ---  ┆ ---  ┆ ---  │
│ i64  ┆ str  ┆ i64  │
╞══════╪══════╪══════╡
│ 1    ┆ 2    ┆ 3    │
│ 2    ┆ 3    ┆ 4    │
└──────┴──────┴──────┘
>>> # How to select col3? which is the last column in df

How can i do this in polars?. I can do df.iloc[:,-1:] to select the last column if it's a pandas dataframe.

Additional info:

>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=11, micro=0, releaselevel='final', serial=0)
>>> import polars
>>> polars.__version__
'0.18.3'

Solution

  • To aid in operatons like these, a polars.selectors module was introduced recently. You can simply use last from this module:

    df.select(cs.last())
    
    shape: (2, 1)
    ┌──────┐
    │ col3 │
    │ ---  │
    │ i64  │
    ╞══════╡
    │ 3    │
    │ 4    │
    └──────┘