Skip to content

BUG: MutliIndex names lost during pivot #36360

Closed
@r7sa

Description

@r7sa
  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Code Sample, a copy-pastable example

d = pd.DataFrame([[1,2,3],[2,2,3],[3,2,3],[4,2,3],[5,2,3]], 
                 columns=pd.MultiIndex.from_tuples([[0, 0, 0], [0, 0, 1], [0, 0, 2]], names=['c1', 'c2', 'c3']),
                 index=pd.MultiIndex.from_tuples([[0, 0, 0, 0, 0, 0, 0],
                                                  [0, 0, 1, 0, 0, 0, 1],
                                                  [0, 1, 0, 0, 0, 1, 0],
                                                  [0, 1, 1, 0, 0, 1, 1],
                                                  [1, 0, 0, 0, 1, 0, 0]
                                                  ], 
                                                 names=['i1', 'i2', 'i3', 'i4', 'i5', 'i6', 'i7']))
e = d.pivot_table(index=['i1',], columns=['i2', 'i3',], values=[(0, 0, 1), (0, 0, 2)], aggfunc=lambda v: v.values[0])
e.columns

result is:

            (0, 0, 1, 0, 1),
            (0, 0, 1, 1, 0),
            (0, 0, 1, 1, 1),
            (0, 0, 2, 0, 0),
            (0, 0, 2, 0, 1),
            (0, 0, 2, 1, 0),
            (0, 0, 2, 1, 1)],
           names=[None, None, None, 'i2', 'i3'])

some names is None, but must be
names=['c1', 'c2', 'c3', 'i2', 'i3'])

Problem description

Problems seems in pandas/core/groupby/generic.py in class DataFrameGroupBy in function _wrap_aggregated_output
Line

name = self._obj_with_exclusions._get_axis(1 - self.axis).name

seems to must be

name_axis = self._obj_with_exclusions._get_axis(1 - self.axis)
name = name_axis.names if isinstance(name_axis, MultiIndex) else name_axis.name

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions