Search code examples
pythonpandasfacebook-prophet

In Python how to use Pandas to manipulate output from Prophet


enter image description herenew to Python, would appreciate any help with Pandas to manipulate output from Prophet Library ( see image ). My input Dataframe has 3 columns, Prophet only takes 2, and my output is 4 columns. Is there also a way to loop back around and run the same for Operators 5 and 6, or do I need to add them sequntially to the code ? Thanks in advance for your help. Gav

import pandas as pd
from fbprophet import Prophet
df = pd.read_csv('C:\path\myfile.csv')
df.columns = ['Operator','ds','y']
df['ds'] = pd.to_datetime(df['ds'])
dfprop=df[df['Operator']==1]
dfprop=dfprop[['ds','y']]
m = Prophet()
m.fit(dfprop)
future = m.make_future_dataframe(periods=158)
forecast = m.predict(future)
forecast
forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(158)
dfout = df.append(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(158))

enter image description here


Solution

  • Cant test this without a reproducible dataset but something like this should do it.

    import pandas as pd
    from fbprophet import Prophet
    df = pd.read_csv('C:\path')
    df.columns = ['Operator','ds','y']
    df['ds'] = pd.to_datetime(df['ds'])
    
    def forecast_data(g):
        data = g[['ds','y']]
        m = Prophet()
        m.fit(data)
        future = m.make_future_dataframe(periods=158)
        forecast = m.predict(future)
        forecast['Operator'] = g['Operator'].iloc[0]
        forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(158)
        dfout = g.append(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(158))
        return dfout
    
    df.groupby('Operator').apply(forecast_data)
    

    apply to the group 'Operator' and create a model for each