[Python] Is there a polars function to dot product two lists?

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

  1. Stack

    Stack Membro Participativo

    I have a dataframe which have list type columns, of equal lengths. I would like to do a dot product on these two columns without having to "explode" the lists (as it would take to much memory).

    The following code gives an error:

    df = pl.DataFrame({
    "b": [[1,2,3], [2,3],[4],[1,2,3],[]],
    "c": [[1,1,1], [2,2],[4],[1,5,6],[]]
    })
    df.with_columns(pl.col('b').list.eval(pl.element().dot(pl.col('b'))).alias('b.c'))


    ComputeError: named columns are not allowed in `list.eval`; consider using `element` or `col("")`


    Desired result:

    df.with_columns(
    dot = np.dot(pl.col('b'), pl.col('c')).list.sum()
    )


    shape: (5, 3)
    ┌───────────┬───────────┬─────┐
    │ b ┆ c ┆ dot │
    │ --- ┆ --- ┆ --- │
    │ list[i64] ┆ list[i64] ┆ i64 │
    ╞═══════════╪═══════════╪═════╡
    │ [1, 2, 3] ┆ [1, 1, 1] ┆ 6 │
    │ [2, 3] ┆ [2, 2] ┆ 10 │
    │ [4] ┆ [4] ┆ 16 │
    │ [1, 2, 3] ┆ [1, 5, 6] ┆ 29 │
    │ [] ┆ [] ┆ 0 │
    └───────────┴───────────┴─────┘

    Continue reading...

Compartilhe esta Página