BUG: groupby dropna=False with nan value in groupby causes ValueError when apply()

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

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

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


Code Sample, a copy-pastable example

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'groups': ['a', 'a', 'b', np.nan],
    'tonnages': [10, 10, 20, 30]
})
dfg = df.groupby('groups', dropna=False)
rv = dfg.apply(lambda grp: pd.DataFrame({'values': list(range(len(grp)))}))

Problem description

ValueError raised on dfg.apply(lambda grp: ...); with the following stacktrace:

../../env3.8/lib/python3.8/site-packages/pandas/core/groupby/groupby.py:859: in apply
    result = self._python_apply_general(f, self._selected_obj)
../../env3.8/lib/python3.8/site-packages/pandas/core/groupby/groupby.py:894: in _python_apply_general
    return self._wrap_applied_output(
../../env3.8/lib/python3.8/site-packages/pandas/core/groupby/generic.py:1230: in _wrap_applied_output
    return self._concat_objects(keys, values, not_indexed_same=not_indexed_same)
../../env3.8/lib/python3.8/site-packages/pandas/core/groupby/groupby.py:1145: in _concat_objects
    result = concat(
../../env3.8/lib/python3.8/site-packages/pandas/core/reshape/concat.py:274: in concat
    op = _Concatenator(
../../env3.8/lib/python3.8/site-packages/pandas/core/reshape/concat.py:454: in __init__
    self.new_axes = self._get_new_axes()
../../env3.8/lib/python3.8/site-packages/pandas/core/reshape/concat.py:519: in _get_new_axes
    return [
../../env3.8/lib/python3.8/site-packages/pandas/core/reshape/concat.py:520: in <listcomp>
    self._get_concat_axis() if i == self.bm_axis else self._get_comb_axis(i)
../../env3.8/lib/python3.8/site-packages/pandas/core/reshape/concat.py:576: in _get_concat_axis
    concat_axis = _make_concat_multiindex(
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

indexes = [RangeIndex(start=0, stop=2, step=1), RangeIndex(start=0, stop=1, step=1), RangeIndex(start=0, stop=1, step=1)]
keys = Index(['a', 'b', nan], dtype='object', name='groups')
levels = [Index(['a', 'b', nan], dtype='object', name='groups')]
names = ['groups']

    def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiIndex:
    
        if (levels is None and isinstance(keys[0], tuple)) or (
            levels is not None and len(levels) > 1
        ):
            zipped = list(zip(*keys))
            if names is None:
                names = [None] * len(zipped)
    
            if levels is None:
                _, levels = factorize_from_iterables(zipped)
            else:
                levels = [ensure_index(x) for x in levels]
        else:
            zipped = [keys]
            if names is None:
                names = [None]
    
            if levels is None:
                levels = [ensure_index(keys)]
            else:
                levels = [ensure_index(x) for x in levels]
    
        if not all_indexes_same(indexes):
            codes_list = []
    
            # things are potentially different sizes, so compute the exact codes
            # for each level and pass those to MultiIndex.from_arrays
    
            for hlevel, level in zip(zipped, levels):
                to_concat = []
                for key, index in zip(hlevel, indexes):
                    mask = level == key
                    if not mask.any():
>                       raise ValueError(f"Key {key} not in level {level}")
E                       ValueError: Key nan not in level Index(['a', 'b', nan], dtype='object', name='groups')

../../env3.8/lib/python3.8/site-packages/pandas/core/reshape/concat.py:631: ValueError

Expected Output

No error should be raised. With the above, if i omit the nan:

df = pd.DataFrame({
    'groups': ['a', 'a', 'b'],
    'tonnages': [10, 10, 20]
})
dfg = df.groupby('groups', dropna=False)
rv = dfg.apply(lambda grp: pd.DataFrame({'values': list(range(len(grp)))}))

Then it works successfully with rv being:

          values
groups          
a      0       0
       1       1
b      0       0

Output of pd.show_versions()

INSTALLED VERSIONS

commit : f2ca0a2
python : 3.8.2.final.0
python-bits : 64
OS : Darwin
OS-release : 18.7.0
Version : Darwin Kernel Version 18.7.0: Thu Jun 18 20:50:10 PDT 2020; root:xnu-4903.278.43~1/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_AU.UTF-8
LOCALE : en_AU.UTF-8

pandas : 1.1.1
numpy : 1.18.4
pytz : 2019.3
dateutil : 2.8.1
pip : 20.1.1
setuptools : 46.4.0
Cython : 0.29.17
pytest : 5.1.1
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : 0.9.6
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : 2.8.3 (dt dec pq3 ext lo64)
jinja2 : 2.11.2
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : 1.3.1
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : 2.7.1
odfpy : None
openpyxl : 1.8.6
pandas_gbq : None
pyarrow : None
pytables : None
pyxlsb : None
s3fs : None
scipy : 1.4.1
sqlalchemy : 1.3.12
tables : 3.6.1
tabulate : None
xarray : None
xlrd : 1.2.0
xlwt : None
numba : None

1 possible answer(s) on “BUG: groupby dropna=False with nan value in groupby causes ValueError when apply()