Dataframe KeyError – not in index

I’m struggling to copy the below stated 3 columns from the non_contras_by_account dataframe columns. Whenever I run this code I get a KeyError that ‘account key’ not in index. This is odd because ‘account_key’ is clearly present in this dataframe.

Any help on this would be much appreciated!

non_contras_by_account = non_contras.groupby('account_key').sum()

non_contra_tab_df = non_contras_by_account[['account_key',value_col,'abs_val']]

KeyError: "[‘account_key’] not in index"

>Solution :

Use as_index=False in the first command to keep groupby from moving it as index:

non_contras_by_account = non_contras.groupby('account_key', as_index=False).sum()

Leave a Reply