5

In Polars 0.13.14, I could create a DataFrame with an all-constant column like this:

import polars as pl

pl.DataFrame(dict(x=pl.repeat(1, 3)))

# shape: (3, 1)
# ┌─────┐
# │ x   │
# │ --- │
# │ i64 │
# ╞═════╡
# │ 1   │
# ├╌╌╌╌╌┤
# │ 1   │
# ├╌╌╌╌╌┤
# │ 1   │
# └─────┘

But in Polars 0.13.15, this is an error

ValueError: Series constructor not called properly.

How do I fill a column with a value in polars?

drhagen
  • 8,331
  • 8
  • 53
  • 82

2 Answers2

5

You might be looking for pl.lit(..)

import polars as pl
df = pl.DataFrame({"a": [1,2,3], "b": [4, 5, 6]})
print(df)
print(df.with_column(pl.lit(1).alias("constant_column")))

This will give you the following output

shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1   ┆ 4   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 2   ┆ 5   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 3   ┆ 6   │
└─────┴─────┘
shape: (3, 3)
┌─────┬─────┬─────────────────┐
│ a   ┆ b   ┆ constant_column │
│ --- ┆ --- ┆ ---             │
│ i64 ┆ i64 ┆ i32             │
╞═════╪═════╪═════════════════╡
│ 1   ┆ 4   ┆ 1               │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 5   ┆ 1               │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ 6   ┆ 1               │
└─────┴─────┴─────────────────┘
Moriarty Snarly
  • 506
  • 5
  • 9
  • 1
    This is kinda not what the OP asked for. Adding a column to an existing `DataFrame` and creating a single column `DataFrame` from scratch is not the same thing. – sobek Oct 15 '22 at 08:11
4

Starting in Polars 0.13.15, repeat became a lazy function by default and lazy functions are not evaluated in the DataFrame constructor. You can get the eager behavior back with the eager=True flag:

import polars as pl

pl.DataFrame(dict(x=pl.repeat(1, 3, eager=True)))

Or you can use a context like:

import polars as pl

pl.DataFrame().with_column(pl.repeat(1, 3).alias('x'))
drhagen
  • 8,331
  • 8
  • 53
  • 82