1

How do I concatenate two string columns horizontally or append a fixed string to a column?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

pl.concat_str is horizontal. There's also pl.format - (.str.concat was renamed to .str.join)
@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.
Feel free to add them to your answer.

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.