[Python] Pandas Pivot_table KeyError when Key is Present

Discussão em 'Python' iniciado por Stack, Julho 14, 2025.

  1. Stack

    Stack Membro Participativo

    I've run this code in an older version of Python, with success; however, we've recently switched to Python 3.9 and I'm getting a KeyError:'RegIndex' on a pivot step for a column that exists in the original dataframe...below is the code sample and dataframe sample.

    myData=df[['ModelYear','RegIndex','ModelIndex','Model','ModelQty','ModelWgt']]
    total = myData.groupby(['RegIndex','Model'])[['ModelQty','ModelWgt']],sum().round(2),reset_index()

    myData = myData.pivot_table(index='ModelYear',
    columns = ['ModelIndex','Model'],
    margins=True,
    margins_name='Total',
    aggfunc=sum,
    fill_value=0)

    Index​
    ModelYear​
    RegIndex​
    ModelIndex​
    Model​
    ModelQty​
    ModelWgt​
    1​
    2001​
    0​
    1​
    F150​
    1000​
    7500​
    2​
    2002​
    0​
    1​
    F150​
    2000​
    7500​
    3​
    2003​
    0​
    1​
    F150​
    1200​
    7500​
    4​
    2004​
    0​
    1​
    F150​
    1750​
    7500​
    5​
    2001​
    0​
    2​
    Silverado​
    2000​
    6500​

    Is the error due to 'RegIndex' not being included in the index of the pivot_table() ? I added it like this: index=['ModelYear','RegIndex'] and it removed the KeyError;however, I don't know if that will alter the original design that worked in the prior version and I'm unsure of the implications. Not sure if there's a better way to go about this.

    Possible solution could be to simply drop the column from the dataframe prior to the pivot_table step. It's strange this error never occurred in the prior version.

    Continue reading...

Compartilhe esta Página