Search code examples
pythonpython-3.xpandasdataframepython-polars

What's the polars equivalent to the pandas `.iloc` method?


I'm looking for the recommended way to select an individual row of a polars.DataFrame by row number: something largely equivalent to pandas.DataFrame's .iloc[[n]] method for a given integer n.

For polars imported as pl and a polars DataFrame df, my current approach would be:

# for example
n = 3

# create row index, filter for individual row, drop the row index.
new_df = (
    df.with_row_index()
    .filter(pl.col('index') == n)
    .select(pl.exclude('index'))
)

I'm migrating from Pandas, and I've read the Pandas-to-Polars migration guide, but a slick solution to this specific case wasn't addressed there. Edit: to clarify, I am looking for an approach that returns a polars.DataFrame object for the chosen row.

Does anyone have something slicker?


Solution

  • This is a very good sheet by: @Liam Brannigan

    Credit to them.

    https://www.rhosignal.com/posts/polars-pandas-cheatsheet/

    A glimse from the sheet:

    enter image description here

    You can find other information related to Filtering Rows using iloc and its equivalent in polars in the sheet.

    enter image description here