Translate from pandas to polars df.groupby('a')['b'].apply(list).to_dict()
- User
Translate from pandas to polars
df.groupby('a')['b'].apply(list).to_dict()
- Assistant
In Polars, you can achieve the equivalent of the Pandas operation using the
groupbyandaggmethods, as well as thelistaggregation function. Here's how to translate the given Pandas code to Polars:pythonimport polars as pl # Example DataFrame df = pl.DataFrame({ "a": ["foo", "bar", "foo", "bar", "baz"], "b": [1, 2, 3, 4, 5] }) # Group by 'a' and aggregate 'b' as lists, then convert to a dictionary result = df.groupby("a").agg(pl.col("b").list()).to_dict(as_series=False)In this code:
df.groupby("a")groups the DataFrame by column 'a'..agg(pl.col("b").list())creates a list of values from column 'b' for each group..to_dict(as_series=False)converts the result to a dictionary format similar to the Pandas output. Theas_series=Falseoption ensures that the dictionary returns plain lists instead of Polars Series.
This replicates your original Pandas operation using Polars.
- User
got TypeError: 'ExprListNameSpace' object is not callable
- Assistant
The error you're encountering indicates that there was some confusion in the method chaining or a potential version mismatch. Let's clarify how to correctly use Polars to achieve the grouping and aggregation.
Here’s the corrected code to translate your original Pandas code to Polars:
pythonimport polars as pl # Create an example DataFrame df = pl.DataFrame({ "a": ["foo", "bar", "foo", "bar", "baz"], "b": [1, 2, 3, 4, 5] }) # Group by 'a' and aggregate 'b' into lists result = df.groupby("a").agg(pl.col("b").list()).to_dict() # If you want the result without Series, use: result_as_dict = {row['a']: row['b'] for row in result['b'].iter_rows()} print(result_as_dict)