13

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?

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. Commented Jan 25, 2024 at 17:55
  • It seems the Polars does not really use an index. The focus in on the data and not the index. Commented Jan 25, 2024 at 18:06
  • But you can set a column as the index via polars.DataFrame.with_row_index Commented Jan 25, 2024 at 18:14

2 Answers 2

26

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

Sign up to request clarification or add additional context in comments.

Comments

1

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 Comments

Thanks for sharing this - I was looking for an approach that returns a dataframe object - I'll clarify in the question.
Oh I'm sorry. I didn't understand that from the original question.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.