How do I concatenate two string columns horizontally or append a fixed string to a column?
1 Answer
Use .add or + on the columns.
df = pl.DataFrame({"x": ["a","d","g"], "y": ["b","e","h"], "z": ["c","f","i"]})
>>> df.with_columns(xa = pl.col("x") + "a")
shape: (3, 4)
┌─────┬─────┬─────┬─────┐
│ x ┆ y ┆ z ┆ xa │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str │
╞═════╪═════╪═════╪═════╡
│ a ┆ b ┆ c ┆ aa │
│ d ┆ e ┆ f ┆ da │
│ g ┆ h ┆ i ┆ ga │
└─────┴─────┴─────┴─────┘
>>> df.with_columns(pl.col("x").add(pl.col("y")).add(pl.col("z")).alias("xyz"))
shape: (3, 4)
┌─────┬─────┬─────┬─────┐
│ x ┆ y ┆ z ┆ xyz │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str │
╞═════╪═════╪═════╪═════╡
│ a ┆ b ┆ c ┆ abc │
│ d ┆ e ┆ f ┆ def │
│ g ┆ h ┆ i ┆ ghi │
└─────┴─────┴─────┴─────┘
Note that str.concat joins strings vertically in a column and is deprecated.
3 Comments
jqurious
qwr
@jqurious yes, that is useful for joining multiple by delimiter. You should post as an answer or I can add it to my answer. It is surprisingly difficult to find info on this from the docs.
jqurious
Feel free to add them to your answer.