1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Row-wise updates in polars

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024 às 15:12.

  1. Stack

    Stack Membro Participativo

    Say I have this dataframe:

    >>> pl.DataFrame([[1,2,3],[4,5,6],[7,8,9]],list('abc'))
    shape: (3, 3)
    ┌─────┬─────┬─────┐
    │ a ┆ b ┆ c │
    │ --- ┆ --- ┆ --- │
    │ i64 ┆ i64 ┆ i64 │
    ╞═════╪═════╪═════╡
    │ 1 ┆ 4 ┆ 7 │
    │ 2 ┆ 5 ┆ 8 │
    │ 3 ┆ 6 ┆ 9 │
    └─────┴─────┴─────┘


    Note that below I'm specifically asking about the case where columns are "unimporant" - i.e. I'm looking for a solution that doesn't necessarily depend on columns being named a, b and c or that there is a certain number of columns.

    I can use the following to update a certain column at a certain row:

    >>> pl.DataFrame([[1,2,3],[4,5,6],[7,8,9]],list('abc')).with_row_index().with_columns(a=pl.when(pl.col('index') == 1).then(42).otherwise(pl.col('a'))).drop('index')
    shape: (3, 3)
    ┌─────┬─────┬─────┐
    │ a ┆ b ┆ c │
    │ --- ┆ --- ┆ --- │
    │ i64 ┆ i64 ┆ i64 │
    ╞═════╪═════╪═════╡
    │ 1 ┆ 4 ┆ 7 │
    │ 42 ┆ 5 ┆ 8 │
    │ 3 ┆ 6 ┆ 9 │
    └─────┴─────┴─────┘


    but that's a bit hard if I don't know that I should be updating a.

    How can I do the following:

    1. Replace the whole row - e.g. I want to replace the 2nd row with 43,42,41:

    ┌─────┬─────┬─────┐
    │ a ┆ b ┆ c │
    │ --- ┆ --- ┆ --- │
    │ i64 ┆ i64 ┆ i64 │
    ╞═════╪═════╪═════╡
    │ 1 ┆ 4 ┆ 7 │
    │ 43 ┆ 42 ┆ 41 │
    │ 3 ┆ 6 ┆ 9 │
    └─────┴─────┴─────┘

    1. Replace any column in a certain row by condition - e.g. I want to negate any values > 4 in 2nd row:

    ┌─────┬─────┬─────┐
    │ a ┆ b ┆ c │
    │ --- ┆ --- ┆ --- │
    │ i64 ┆ i64 ┆ i64 │
    ╞═════╪═════╪═════╡
    │ 1 ┆ 4 ┆ 7 │
    │ 2 ┆ -5 ┆ -8 │
    │ 3 ┆ 6 ┆ 9 │
    └─────┴─────┴─────┘

    Continue reading...

Compartilhe esta Página