[Python] Pandas isin function in polars

Discussão em 'Python' iniciado por Stack, Setembro 16, 2024.

  1. Stack

    Stack Membro Participativo

    Once in a while I get to the point where I need to run the following line:

    DF['is_flagged'] = DF['id'].isin(DF2[DF2['flag']==1]['id'])


    Lately I started using polars, and I wonder how to convert it easily to polars.

    For example:

    df1 = pl.DataFrame({
    'Animal_id': [1, 2, 3, 4, 5, 6, 7],
    'age': [4, 6, 3, 8, 3, 8, 9] })

    df2 = pl.DataFrame({
    'Animal_id': [1, 2, 3, 4, 5, 6, 7],
    'Animal_type': ['cat', 'dog', 'cat', 'cat', 'dog', 'dog', 'cat'] })


    Expected output:

    shape: (7, 3)
    ┌───────────┬─────┬────────┐
    │ animal_id ┆ age ┆ is_dog │
    │ --- ┆ --- ┆ --- │
    │ i64 ┆ i64 ┆ i64 │
    ╞═══════════╪═════╪════════╡
    │ 1 ┆ 4 ┆ 0 │
    │ 2 ┆ 6 ┆ 1 │
    │ 3 ┆ 3 ┆ 0 │
    │ 4 ┆ 8 ┆ 0 │
    │ 5 ┆ 3 ┆ 1 │
    │ 6 ┆ 8 ┆ 1 │
    │ 7 ┆ 9 ┆ 0 │
    └───────────┴─────┴────────┘


    Without using flag and then join

    I tried to use the is_in() function but this didn’t worked.

    Continue reading...

Compartilhe esta Página