Skip to content

pivot_table throws exception with multiple aggregations per column and margins=True #12210

@grutts

Description

@grutts

When applying multiple aggregations to columns and setting margins=True I receive a KeyError. I believe that because multiple aggregations are applied the columns become a MultiIndex, which is unexpected when computing margins.

>>> import pandas as pd >>> import numpy as np >>> import random >>> df = pd.DataFrame({'random1': [random.random() for i in range(10)], 'random2': [random.random() for i in range(10)], 'type': ['duck', 'bird']*5}, index=range(10,20)) >>> df.pivot_table(index='type', aggfunc={'random1': [np.median, np.mean], 'random2': np.sum}, margins=True) KeyError Traceback (most recent call last) <ipython-input> in <module>() 3 aggfunc={'random1': [np.median, np.mean], 4 'random2': np.sum}, ----> 5 margins=True) /pandas/util/decorators.pyc in wrapper(*args, **kwargs) 86 else: 87 kwargs[new_arg_name] = new_arg_value ---> 88 return func(*args, **kwargs) 89 return wrapper 90 return _deprecate_kwarg /pandas/util/decorators.pyc in wrapper(*args, **kwargs) 86 else: 87 kwargs[new_arg_name] = new_arg_value ---> 88 return func(*args, **kwargs) 89 return wrapper 90 return _deprecate_kwarg /pandas/tools/pivot.pyc in pivot_table(data, values, index, columns, aggfunc, fill_value, margins, dropna) 145 if margins: 146 table = _add_margins(table, data, values, rows=index, --> 147 cols=columns, aggfunc=aggfunc) 148 149 # discard the top level /pandas/tools/pivot.pyc in _add_margins(table, data, values, rows, cols, aggfunc) 189 row_margin[k] = grand_margin[k] 190 else: --> 191 row_margin[k] = grand_margin[k[0]] 192 193 margin_dummy = DataFrame(row_margin, columns=[key]).T KeyError: 'random1'

The exact same error occurs with

aggfunc={'random1': {'median': np.median, 'mean': np.mean}, 'random2': np.sum}

These errors do not occur when margins=False
This is using pandas version 0.15.2. I have not seen any changes which would lead me to believe it is be fixed in master.

Happy to create a PR, although I haven't done one before.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugReshapingConcat, Merge/Join, Stack/Unstack, Explode

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions