[Python] rewrite function from Pandas to Polars

Discussão em 'Python' iniciado por Stack, Março 12, 2025.

  1. Stack

    Stack Membro Participativo

    Please help rewrite to polars:

    df = pd.DataFrame({
    "fructs": ["apple", "apple", "apple", "banana", "banana", "banana", "banana"],
    "g": [1, 1, 1, 2, 2, 2, 5],
    "a": [2, 4, 5, 190, 1, 4, 1],
    "b": [1, 3, 2, 1, 43, 3, 1]
    })

    def _calculate_coefficient(group: pd.DataFrame) -> float:
    model = smf.ols("a ~ g + b", data=group).fit() # this line might be in pandas
    coef: float = model.params["g"]
    return coef


    markdown_coefficients = (
    df.groupby(["fructs"], as_index=False)
    .apply(_calculate_coefficient)
    .rename(columns={None: "elast_discount_coef"})
    )


    Expected result:

    result = pd.DataFrame({
    "fructs": ["apple", "banana"],
    "elast_discount_coef": [0.833333, -33.570071],
    })


    I need to calculate coefficient for each group

    Continue reading...

Compartilhe esta Página