notes.kagcc

Notes on polars

polars: 複数列から新たなstringを作って列にする

polars.concat_str

挙げられている例

df = pl.DataFrame(
    {
        "a": [1, 2, 3],
        "b": ["dogs", "cats", None],
        "c": ["play", "swim", "walk"],
    }
)
df.with_columns(
    pl.concat_str(
        [
            pl.col("a") * 2,
            pl.col("b"),
            pl.col("c"),
        ],
        separator=" ",
    ).alias("full_sentence"),
)
shape: (3, 4)
┌─────┬──────┬──────┬───────────────┐
│ a   ┆ b    ┆ c    ┆ full_sentence │
│ --- ┆ ---  ┆ ---  ┆ ---           │
│ i64 ┆ str  ┆ str  ┆ str           │
╞═════╪══════╪══════╪═══════════════╡
│ 1   ┆ dogs ┆ play ┆ 2 dogs play   │
│ 2   ┆ cats ┆ swim ┆ 4 cats swim   │
│ 3   ┆ null ┆ walk ┆ null          │
└─────┴──────┴──────┴───────────────┘

str じゃない型のも文字列に変換はしてくれるみたい. nullの扱いは ignore_nulls で可能.

また,polars.format もあるが,python の f-string とかはまだみたいなので,例えばmonthday を文字列として引っ付けるには (zero-padding の点で) 不便がある.とりあえずは, map_elements を使うのが妥当なのかも.stackoverflow に例がある.

df.with_columns(
    pl.col("size").map_elements(lambda x: f"{x:,.2f}", return_dtype=pl.String)
)