Repository: pandas-dev/pandas

Issue:
Groupby on multiindex with missing data in group keys raises IndexError
#### Code Sample, a copy-pastable example if possible

```python
foo= pd.DataFrame([['x', np.nan, 1]], columns = ['A', 'B', 'C']).set_index(['A', 'B'])
foo.groupby(level = ['A', 'B']).C.sum()
IndexError: cannot do a non-empty take from an empty axes.

# while this is expected, as a comparison
bar = pd.DataFrame([['x', np.nan, 1]], columns = ['A', 'B', 'C'])
bar.groupby(level = ['A', 'B']).C.sum()
Series([], Name: C, dtype: int64)
```
#### Problem description
It would be better if pandas can either return the same result as the 'bar' case, or raise another meaningful exception and document this case somewhere (e.g. [here](http://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby-missing)))

#### Expected Output
Series([], Name: C, dtype: int64)
#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit: None
python: 2.7.12.final.0
python-bits: 64
OS: Linux
OS-release: 3.10.0-229.el7.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8

pandas: 0.18.1
nose: None
pip: None
setuptools: None
Cython: None
numpy: 1.10.4
scipy: None
statsmodels: None
xarray: None
IPython: None
sphinx: None
patsy: None
dateutil: 2.4.2
pytz: 2016.4
blosc: None
bottleneck: 1.0.0
tables: None
numexpr: 2.4.6
matplotlib: None
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
httplib2: 0.9.2
apiclient: 1.2
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: None
boto: 2.22.1
pandas_datareader: None

</details>



Discussion:
Yeah, I think this should return an empty series.
May i take a look?
There are 2 `IndexError: cannot do a non-empty take from an empty axes.` in codebase:
- `SparseArray. _take_with_fill()`
https://github.com/pandas-dev/pandas/blob/489d1ff8a1683f7f5549108dc7b04e43b5f32965/pandas/core/arrays/sparse.py#L1180
- `SparseArray. _take_without_fill()`
https://github.com/pandas-dev/pandas/blob/489d1ff8a1683f7f5549108dc7b04e43b5f32965/pandas/core/arrays/sparse.py#L1230

Why don't we create a new Exception such as `EmptyAxesTakeFailedIndexError` from this `IndexError` and just catch this at `groupers`? (Same strategy with #27945, but narrow down.)

Resolving patch:
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1308,7 +1308,10 @@ def _get_grouper_for_level(self, mapper, level):
             # Remove unobserved levels from level_index
             level_index = level_index.take(uniques)
 
-        grouper = level_index.take(codes)
+        if len(level_index):
+            grouper = level_index.take(codes)
+        else:
+            grouper = level_index.take(codes, fill_value=True)
 
         return grouper, codes, level_index
 


Test patch:
diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py
--- a/pandas/tests/groupby/test_grouping.py
+++ b/pandas/tests/groupby/test_grouping.py
@@ -628,6 +628,24 @@ def test_groupby_empty(self):
         # check name
         assert s.groupby(s).grouper.names == ["name"]
 
+    def test_groupby_level_index_value_all_na(self):
+        # issue 20519
+        df = DataFrame(
+            [["x", np.nan, 10], [None, np.nan, 20]], columns=["A", "B", "C"]
+        ).set_index(["A", "B"])
+        result = df.groupby(level=["A", "B"]).sum()
+        expected = DataFrame(
+            data=[],
+            index=MultiIndex(
+                levels=[Index(["x"], dtype="object"), Index([], dtype="float64")],
+                codes=[[], []],
+                names=["A", "B"],
+            ),
+            columns=["C"],
+            dtype="int64",
+        )
+        tm.assert_frame_equal(result, expected)
+
 
 # get_group
 # --------------------------------