0

Python no longer uses panel. I am not skilled enough to think of an alternative and hoping someone knows of a work around. I have been using the code below for some time but after an update it no longer works. I would prefer to update the code then revert back to older unsupported versions. the issue i am having is panel is deactivated. can you see a work around to this problem? for what i am trying to accomplish is find the beta of a stock. i have taken the code from the following link

Efficient Python Pandas Stock Beta Calculation on Many Dataframes

def roll(df, w):
 # stack df.values w-times shifted once at each stack
 roll_array = np.dstack([df.values[i:i+w, :] for i in range(len(df.index) - w + 1)]).T
 # roll_array is now a 3-D array and can be read into
 # a pandas panel object
 panel = pd.Panel(roll_array, 
                 items=df.index[w-1:],
                 major_axis=df.columns,
                 minor_axis=pd.Index(range(w), name='roll'))
 # convert to dataframe and pivot + groupby
 # is now ready for any action normally performed
 # on a groupby object
 return panel.to_frame().unstack().T.groupby(level=0)

rdf = roll(df, 156)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Panels were replaced by multindex in later versions of pandas (see here https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.set_levels.html) – zglin Oct 15 '19 at 15:48

1 Answers1

0

found the answer. thought i would post in the off chance someone needed it.

from numpy.lib.stride_tricks import as_strided as stride
import pandas as pd

def roll(df, w, **kwargs):
    v = df.values
    d0, d1 = v.shape
    s0, s1 = v.strides

    a = stride(v, (d0 - (w - 1), w, d1), (s0, s0, s1))

    rolled_df = pd.concat({
        row: pd.DataFrame(values, columns=df.columns)
        for row, values in zip(df.index, a)
    })

    return rolled_df.groupby(level=0, **kwargs)

roll(df, 2).mean()

link to answer i found.

link to answer