Search code examples
pythonpandasmaxpanelvectorization

python pandas - identify row of rolling maximum value from panel?


Does Panel have anything like pan.idxmax(axis='items') which could return the row # or index for the largest value as in the question linked below which piRSquared answered perfectly?

Link to original question


Solution

  • consider the pd.Panel p

    dfs = dict(
        one=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
        two=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
        three=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
    )
    
    p = pd.Panel(dfs)
    p.to_frame().unstack()
    

    enter image description here


    the pd.Panel object doesn't have an idxmax method. But the underlying numpy array does have the argmax method. I've built this custom function to leverage that.

    def idxmax(pn, axis=0):
        indices = pd.Series(['items', 'major_axis', 'minor_axis'])
        idx, col = indices.drop(axis)
        return pd.DataFrame(pn.values.argmax(axis),
                            pn.__getattribute__(idx),
                            pn.__getattribute__(col))
    

    usage

    idxmax(p, 0)
    

    enter image description here

    idxmax(p, 1)
    

    enter image description here

    idxmax(p, 2)
    

    enter image description here