[Python] Casting expression result

Discussão em 'Python' iniciado por Stack, Dezembro 9, 2024.

  1. Stack

    Stack Membro Participativo

    Would it be possible to cast an expression into a specific datatype without casting the source columns?

    Consider the following frame:

    df = pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, schema={'A': pl.UInt8, 'B': pl.UInt8})

    ┌─────┬─────┐
    │ A ┆ B │
    │ --- ┆ --- │
    │ u8 ┆ u8 │
    ╞═════╪═════╡
    │ 1 ┆ 4 │
    │ 2 ┆ 5 │
    │ 3 ┆ 6 │
    └─────┴─────┘


    Now using an expression:

    df = df.with_columns((pl.col("A") - pl.col("B")).alias("C"))

    ┌─────┬─────┬─────┐
    │ A ┆ B ┆ C │
    │ --- ┆ --- ┆ --- │
    │ u8 ┆ u8 ┆ u8 │
    ╞═════╪═════╪═════╡
    │ 1 ┆ 4 ┆ 253 │
    │ 2 ┆ 5 ┆ 253 │
    │ 3 ┆ 6 ┆ 253 │
    └─────┴─────┴─────┘


    This is obviously correct in comp-sci terms but not practical. Can I only resolve this by first casting "A" and "B" to a signed integer or is there a better/more concise way?

    Continue reading...

Compartilhe esta Página