Skip to content

Inconsistent behavior of index when grouping a multiindex series of length two #26105

Closed
@brian-c-ogorman

Description

@brian-c-ogorman

Code Sample, a copy-pastable example if possible

import pandas as pd

df = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5], 'C': [6, 7, 8]})
df = df.set_index(['A', 'B'])
c = df.C

# series with multiindex and two rows:
#
c[:2].groupby(['A', 'B']).sum()
#
# expected output
# A  B
# 0  3    6
# 1  4    7
# Name: C, dtype: int64
#
# actual output:
# A    6
# B    7
# Name: C, dtype: int64

# series with three rows:
#
c.groupby(['A', 'B']).sum()
#
# expected and actual output:
# A  B
# 0  3    6
# 1  4    7
# 2  5    8
# Name: C, dtype: int64

# as a dataframe with two rows and one column:
#
df[:2].groupby(['A', 'B']).sum().C
# expected and actual output:
# A  B
# 0  3    6
# 1  4    7
# Name: C, dtype: int64

Problem description

When doing a groupby and aggregation on a multi-index Series, if the length of the series is two, the index of the output is incorrect.

The behavior is unexpected and inconsistent with other operations that would be expected to produce the same output:

  • for a multi-index DataFrame of two rows and a single column (C), performing a groupby, aggregation and returning the column (C) as a series should be the same as performing the groupby and aggregation on that Series (C).

  • performing the groupby and aggregation on a multi-index series with at least three rows yields the expected output and is consistent with a single column DataFrame.

Expected Output

# c[:2].groupby(['A', 'B']).sum()
#
A  B
0  3    6
1  4    7
Name: C, dtype: int64

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.7.3.final.0
python-bits: 64
OS: Darwin
OS-release: 18.2.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.24.2
pytest: None
pip: 19.0.3
setuptools: 41.0.0
Cython: None
numpy: 1.16.2
scipy: None
pyarrow: None
xarray: None
IPython: None
sphinx: None
patsy: None
dateutil: 2.8.0
pytz: 2018.9
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: None
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml.etree: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: None
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
gcsfs: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions