Python Forum
How to run a linear model by group in Python?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to run a linear model by group in Python?
#1
Dear all,
I’m beginning with Python that I need to use to run a linear model for the dataset below :
Output:
Location Y X1 X2 1 32 1 1 1 44 1 2 1 58 1 3 1 76 2 1 1 73 2 2 1 37 2 3 1 52 3 1 1 78 3 2 1 60 3 3 2 93 1 1 2 78 1 2 2 25 1 3 2 97 2 1 2 85 2 2 2 60 2 3 2 70 3 1 2 62 3 2 2 95 3 3
My target is to run a linear model as follows :
Y ~ X1 + X2
X1 and X2 are categorical variables
And for that the following code gave me exactly what I need :
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.formula.api import ols
import scipy.stats as stats

df = pd.DataFrame(dataset)
reg = ols('Y ~ C(X1) + C(X2)', data=df).fit() 
df['fitted_values'] = reg.fittedvalues
result = reg.outlier_test()
df['student_resid'] = result.student_resid
What I’m not able to do is to run this code by ‘Location’, and get my columns 'fitted_values' and 'student_resid' accordingly.
Any help is highly appreciated.
Thanks a lot in advance.
Larz60+ write Oct-18-2023, 07:49 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
I modifed for you this time. Please use BBCode tags on future posts.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  LDA Model prepare() method failure in Python noerkes 0 335 Feb-22-2024, 01:42 PM
Last Post: noerkes
  issue displaying summary of whole keras CNN model on TensorFlow with python Afrodizzyjack 0 1,663 Oct-27-2021, 04:07 PM
Last Post: Afrodizzyjack
  General linear model with repeated measures Ziv1279 1 2,578 Dec-20-2020, 11:45 PM
Last Post: PsyPy
  How to build linear regression by implementing Gradient Descent using only linear alg PythonSpeaker 1 2,205 Dec-01-2019, 05:35 PM
Last Post: Larz60+
  arima model error in python wissam1974 0 4,225 Jan-23-2019, 09:37 AM
Last Post: wissam1974
  Solve a system of non-linear equations in Python (scipy.optimize.fsolve) drudox 7 22,751 Aug-18-2018, 02:27 AM
Last Post: scidam
  How to group variables & check correlation of group variables wrt single variable SriRajesh 2 2,978 May-23-2018, 03:01 PM
Last Post: SriRajesh
  How to use a pmml model in Python FlamingGuava 3 13,411 Aug-05-2017, 05:15 PM
Last Post: radioactive9

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020