Skip to content

ENH:Return new Series when missing data in group keys is #27945

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.25.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ Indexing
- Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`)
- Break reference cycle involving :class:`Index` and other index classes to allow garbage collection of index objects without running the GC. (:issue:`27585`, :issue:`27840`)
- Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`).
-
- `IndexError` would not raised if group keys are nan value (:issue:`20519`)

Missing
^^^^^^^
Expand Down
8 changes: 7 additions & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -873,7 +873,13 @@ def _assert_take_fillable(
values, indices, allow_fill=allow_fill, fill_value=na_value
)
else:
taken = values.take(indices)
try:
taken = values.take(indices)
except IndexError:
if not values.tolist():
return []

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about the empty series for this.

else:
raise
return taken

_index_shared_docs[
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2240,6 +2240,25 @@ def test_groupby(self):

tm.assert_dict_equal(result, expected)

def test_groupby_nan_index_value(self):
df = pd.DataFrame([["x", np.nan, 1]], columns=["A", "B", "C"]).set_index(
["A", "B"]
)
result = df.groupby(level=["A", "B"]).C.sum()
s = Series([])
s.name = "C"
expected = s.astype("int64")
tm.assert_series_equal(result, expected)

df = pd.DataFrame(
[["x", np.nan, 1, 2], [None, "y", 3, 4]], columns=["A", "B", "C", "D"]
).set_index(["A", "B", "C"])
result = df.groupby(level=["A", "B"]).D.sum()
s = Series([])
s.name = "D"
expected = s.astype("int64")
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize(
"mi,expected",
[
Expand Down