Reputation: 687
I am currently creating a new column in a polars data frame using
predictions = [10, 20, 30, 40, 50]
df['predictions'] = predictions
where predictions
is a numpy array or list containing values I computed with another tool.
However, polars throws a warning, that this option will be deprecated.
How can the same result be achieved using .with_columns()
?
Upvotes: 26
Views: 24340
Reputation: 1138
You can now also pass numpy arrays in directly. E.g,
df = pl.DataFrame({"x": [0, 1, 2, 3, 4]})
p1 = [10, 20, 30, 40, 50]
p2 = np.array(p1)
df.with_columns(
p1=pl.Series(p1), # For python lists, construct a Series
p2=p2, # For numpy arrays, you can pass them directly
)
# shape: (5, 3)
# ┌─────┬─────┬─────┐
# │ x ┆ p1 ┆ p2 │
# │ --- ┆ --- ┆ --- │
# │ i64 ┆ i64 ┆ i64 │
# ╞═════╪═════╪═════╡
# │ 0 ┆ 10 ┆ 10 │
# │ 1 ┆ 20 ┆ 20 │
# │ 2 ┆ 30 ┆ 30 │
# │ 3 ┆ 40 ┆ 40 │
# │ 4 ┆ 50 ┆ 50 │
# └─────┴─────┴─────┘
Upvotes: 4
Reputation: 687
The values in the numpy array or list predictions
can be add to a polars table using:
predictions = [10, 20, 30, 40, 50]
df.with_columns(pl.Series(name="predictions", values=predictions))
Upvotes: 38