[Python] How to apply linear regression to subsets of a dataframe using groupby

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

  1. Stack

    Stack Membro Participativo

    I want to apply linear regression and predict values to subsets of my original data by V1, V2, V3, V4, V5, and V6. Then I want to store dataframe with names: V1, V2, V3, V4, V5, V6, time, Predicted value. How to achieve it effificiently? What I have now gives me an object that is hard to further work with.

    def model(df):
    X = df['time'].to_numpy().reshape((-1, 1))
    Y = df['speed'].to_numpy()
    X_new = np.arange(1, 60, 1).reshape((-1, 1))
    return np.squeeze(LinearRegression().fit(X, Y).predict(X_new))

    def group_predictions(df):
    return df.groupby(['V1', 'V2', 'V3', 'V4', 'V5','V6']).apply(model)

    Continue reading...

Compartilhe esta Página