3

I have a simple dataframe look like this:

import polars as pl

df = pl.DataFrame({ 
    'ref': ['a', 'b', 'c', 'd', 'e', 'f'], 
    'idx': [4, 3, 1, 6, 2, 5], 
})

How can I obtain the result as creating a new column as ref[idx], which is dynamic index from another column?

out = pl.DataFrame({     
    'ref': ['a', 'b', 'c', 'd', 'e', 'f'],     
    'idx': [4, 3, 1, 6, 2, 5],     
    'ref[idx]': ['d', 'c', 'a', 'f', 'b', 'e'], 
})
shape: (6, 3)
┌─────┬─────┬──────────┐
│ ref ┆ idx ┆ ref[idx] │
│ --- ┆ --- ┆ ---      │
│ str ┆ i64 ┆ str      │
╞═════╪═════╪══════════╡
│ a   ┆ 4   ┆ d        │
│ b   ┆ 3   ┆ c        │
│ c   ┆ 1   ┆ a        │
│ d   ┆ 6   ┆ f        │
│ e   ┆ 2   ┆ b        │
│ f   ┆ 5   ┆ e        │
└─────┴─────┴──────────┘

3 Answers 3

4

Polars has .get() / .gather() expressions for extracting values by index.

df.with_columns(
    pl.col("ref").get(pl.col("idx") - 1).alias("ref[idx]")
)
shape: (6, 3)
┌─────┬─────┬──────────┐
│ ref ┆ idx ┆ ref[idx] │
│ --- ┆ --- ┆ ---      │
│ str ┆ i64 ┆ str      │
╞═════╪═════╪══════════╡
│ a   ┆ 4   ┆ d        │
│ b   ┆ 3   ┆ c        │
│ c   ┆ 1   ┆ a        │
│ d   ┆ 6   ┆ f        │
│ e   ┆ 2   ┆ b        │
│ f   ┆ 5   ┆ e        │
└─────┴─────┴──────────┘
Sign up to request clarification or add additional context in comments.

Comments

1

The DataFrame.with_columns() method could be used to add another column. Subtract one from idx for 0-based indexing.

>>> df.with_columns(**{'ref[idx]': df['ref'][df['idx']-1]})
shape: (6, 3)
┌─────┬─────┬──────────┐
│ ref ┆ idx ┆ ref[idx] │
│ --- ┆ --- ┆ ---      │
│ str ┆ i64 ┆ str      │
╞═════╪═════╪══════════╡
│ a   ┆ 4   ┆ d        │
│ b   ┆ 3   ┆ c        │
│ c   ┆ 1   ┆ a        │
│ d   ┆ 6   ┆ f        │
│ e   ┆ 2   ┆ b        │
│ f   ┆ 5   ┆ e        │
└─────┴─────┴──────────┘

3 Comments

Thank you very much for the prompt response, may I also ask how can u format the dataframe like the one in your answer?
That’s just how they pretty print by default in IPython.
Note that df["col"] series operations will not work in Lazy mode
1

You could use a join,

right = df.select(pl.row_index("index")+1, pl.col("ref").alias("ref[index]"))

df.join(right, left_on="idx", right_on="index")

Comments

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.