Skip to content

groupby() drops categorical columns when aggregating with isna() #29837

Closed
@xujiboy

Description

@xujiboy

Code Sample, a copy-pastable example if possible

df = pd.DataFrame({'A': [1, 1, 1, 1],
                   'B': [1, 2, 1, 2],
                   'numerical_col': [.1, .2, np.nan, .3],
                   'object_col': ['foo','bar','foo','fee'],
                   'categorical_col': ['foo','bar','foo','fee']
                  })

df = df.astype({'categorical_col':'category'})

df.groupby(['A','B']).agg(lambda df: df.isna().sum())

#		numerical_col	object_col
# A	B		
# 1	1	1.0                   0
#       2	0.0	              0

Problem description

The categorical column "categorical_col" is expected to survive the aggregation, however, it gets dropped.

Expected Output

#		numerical_col	object_col categorical_col
# A	B		
# 1	1	1.0                   0                 0
#       2	0.0	              0                 0

Output of pd.show_versions()

[paste the output of pd.show_versions() here below this line]
INSTALLED VERSIONS

commit: None
python: 3.7.1.final.0
python-bits: 64
OS: Linux
OS-release: 3.10.0-693.11.6.el7.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.23.4
pytest: 4.3.1
pip: 19.3.1
setuptools: 40.6.3
Cython: None
numpy: 1.15.4
scipy: 1.1.0
pyarrow: 0.11.1
xarray: None
IPython: 7.1.1
sphinx: None
patsy: 0.5.1
dateutil: 2.7.5
pytz: 2018.7
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 3.0.2
openpyxl: 2.6.1
xlrd: 1.2.0
xlwt: 1.3.0
xlsxwriter: 1.1.5
lxml: 4.3.0
bs4: None
html5lib: None
sqlalchemy: 1.2.13
pymysql: 0.9.3
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: 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