xiaodai
xiaodai

Reputation: 16064

How do I assign a new column to polars dataframe?

In polars, I am trying to create a new column I already know the values of the columns and I just want to add a column with those values. Below is the code

import polars as pl

df = pl.DataFrame({"a": [1, 2], "b": [4, 5]})

english_titles = ["ok", "meh"]

df.with_columns(pl.lit(english_titles).alias("english_title"))

But the above doesn't work and I think it's because I am using pl.lit wrongly

Upvotes: 4

Views: 4129

Answers (1)

jqurious
jqurious

Reputation: 21580

A column is a Series

>>> type(df.get_column("a"))
polars.internals.series.series.Series

Meaning you can use pl.Series instead of pl.lit

>>> df.with_columns(english_title = pl.Series(english_titles))
shape: (2, 3)
┌─────┬─────┬───────────────┐
│ a   ┆ b   ┆ english_title │
│ --- ┆ --- ┆ ---           │
│ i64 ┆ i64 ┆ str           │
╞═════╪═════╪═══════════════╡
│ 1   ┆ 4   ┆ ok            │
│ 2   ┆ 5   ┆ meh           │
└─────┴─────┴───────────────┘

Upvotes: 7

Related Questions