Skip to content

Groupby + sum by multiple columns on an empty DataFrame drops list of columns #15106

Closed
@karatheodory

Description

@karatheodory

Code Sample

import pandas as pd

print pd.DataFrame(data=[[1,2,3]], columns=['A', 'B', 'C'])\
    .groupby(['A', 'B'])\
    .sum()\
    .reset_index()\
    .columns\
    .tolist()
# ['A', 'B', 'C']

print pd.DataFrame(data=[], columns=['A', 'B', 'C'])\
    .groupby(['A'])\
    .sum()\
    .reset_index()\
    .columns\
    .tolist()
# ['A', 'B', 'C']

print pd.DataFrame(data=[], columns=['A', 'B', 'C'])\
    .groupby(['A', 'B'])\
    .sum()\
    .reset_index()\
    .columns\
    .tolist()
# ['index']

Problem description

As the original list of columns is lost in the second case, I have to handle empty data frames differently, or add columns back by myself, both of which are inconvenient.

Expected Output

The list of columns is expected to be equal to the original one from data frame

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 2.7.12.final.0
python-bits: 64
OS: Linux
OS-release: 4.4.0-57-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: None.None

pandas: 0.19.1
nose: 1.3.7
pip: 9.0.1
setuptools: 28.8.0
Cython: None
numpy: 1.11.2
scipy: None
statsmodels: None
xarray: None
IPython: 5.1.0
sphinx: None
patsy: None
dateutil: 2.6.0
pytz: 2016.7
blosc: None
bottleneck: None
tables: None
numexpr: None
matplotlib: 1.5.3
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
httplib2: 0.9.2
apiclient: None
sqlalchemy: 1.1.4
pymysql: None
psycopg2: 2.6.2 (dt dec pq3 ext lo64)
jinja2: 2.8
boto: None
pandas_datareader: None

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