8

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 count, filter for individual row, drop the row count.
new_df = (
    df.with_row_count()
    .filter(pl.col('row_nr') == n)
    .select(pl.exclude('row_nr'))
)

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?

3
  • It would probably depend on what you're doing with the row. For "quick", "interactive" usage df[3] works - but wouldn't be "recommended" if you were composing larger expressions.
    – jqurious
    Commented Jan 25 at 17:55
  • It seems the Polars does not really use an index. The focus in on the data and not the index.
    – Cam
    Commented Jan 25 at 18:06
  • But you can set a column as the index via polars.DataFrame.with_row_index
    – Cam
    Commented Jan 25 at 18:14

2 Answers 2

13

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

0
0

I guess, the direct equivalent of .iloc from is the .row() method in .

If you have a dataframe, df:

df = pl.DataFrame(
    {
        "foo": [1, 2, 3],
        "bar": [6, 7, 8],
        "ham": ["a", "b", "c"],
    }
)

Here's how you'd access a row:

df.row(2)
(3, 8, 'c')
2
  • Thanks for sharing this - I was looking for an approach that returns a dataframe object - I'll clarify in the question.
    – montol
    Commented Jan 25 at 18:27
  • Oh I'm sorry. I didn't understand that from the original question.
    – Ro.oT
    Commented Jan 25 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.