Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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/v1.6.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ Plotting

Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
-
- Bug in :meth:`DataFrameGroupBy.sample` raises ``ValueError`` when the object is empty (:issue:`48459`)
-

Reshaping
Expand Down
3 changes: 3 additions & 0 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -4256,6 +4256,9 @@ def sample(
2 blue 2
0 red 0
""" # noqa:E501
if self._selected_obj.empty:
# GH48459 prevent ValueError when object is empty
return self._selected_obj
size = sample.process_sampling_size(n, frac, replace)
if weights is not None:
weights_arr = sample.preprocess_weights(
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/groupby/test_sample.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,10 @@ def test_groupby_sample_with_selections():
result = df.groupby("a")[["b", "c"]].sample(n=None, frac=None)
expected = DataFrame({"b": [1, 2], "c": [1, 2]}, index=result.index)
tm.assert_frame_equal(result, expected)


def test_groupby_sample_with_empty_inputs():
result = DataFrame({"a": [], "b": []})
expected = result.groupby("a").sample()
Copy link
Member

Choose a reason for hiding this comment

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

nit: result should be the result that is being tested, expected should be what we expect. Can you switch these?


tm.assert_frame_equal(result, expected)