Linear regression using Python

Hello there:



 I am trying to use linear regression in python, in order to mar a forecast but I am stack in an error, the code I am using is the following:





import numpy as np

import pandas as pd

import datetime

from datetime import datetime

import pytz

import time

import os

from scipy import stats





def linear_forecast(y):

    # number of observations/points

    x = np.arange(y.size)

    n = np.size(x)

    # mean of x and y vector

    m_x = np.mean(x)

    m_y = np.mean(y)

    # calculating cross-deviation and deviation about x

    SS_xy = np.sum(yx) - nm_ym_x

    SS_xx = np.sum(x
x) - nm_xm_x

    # calculating regression coefficients

    slope = SS_xy / SS_xx

    intercept = m_y - (slope)m_x

    forecast = (y.size)
(slope) + intercept

    return (forecast)



So I  used a Dataframe in order to try out the code:



data = [float(700),float(782.4),float(814.7)]

df = pd.DataFrame(data)



I defined this dataframe in order to use the function I previously defined:



linear_forecast(df)



And I got the following error:



ValueError: Unable to coerce to Series, length must be 1: given 3



I don't know how to fix thid…Can you please help me???



Thanks a lot

 

Hi Ghery, 



You are trying to input a dataframe to the function 'linear_forecast()'. Instead, you need to pass a 'series' such as a column of the dataframe as an input. 



So, instead of linear_forecast(df), try linear_forecast(df[0]), and you will get the forecast as the output.



Thanks, I hope this helps.



 

Thank you