Skip to content

Commit 122cd07

Browse files
authored
BUG: fix valueError for groupby with empty inputs when sample method is called (#48484)
* fix valueError for empty inputs for groupby sample * add to whatsnew/v1.6.0.rst doc * refactor test for groupby sample * fix duplicate assert in test
1 parent 28bf7f2 commit 122cd07

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

doc/source/whatsnew/v1.6.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ Plotting
189189

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

195195
Reshaping

pandas/core/groupby/groupby.py

+3
Original file line numberDiff line numberDiff line change
@@ -4256,6 +4256,9 @@ def sample(
42564256
2 blue 2
42574257
0 red 0
42584258
""" # noqa:E501
4259+
if self._selected_obj.empty:
4260+
# GH48459 prevent ValueError when object is empty
4261+
return self._selected_obj
42594262
size = sample.process_sampling_size(n, frac, replace)
42604263
if weights is not None:
42614264
weights_arr = sample.preprocess_weights(

pandas/tests/groupby/test_sample.py

+10
Original file line numberDiff line numberDiff line change
@@ -142,3 +142,13 @@ def test_groupby_sample_with_selections():
142142
result = df.groupby("a")[["b", "c"]].sample(n=None, frac=None)
143143
expected = DataFrame({"b": [1, 2], "c": [1, 2]}, index=result.index)
144144
tm.assert_frame_equal(result, expected)
145+
146+
147+
def test_groupby_sample_with_empty_inputs():
148+
# GH48459
149+
df = DataFrame({"a": [], "b": []})
150+
groupby_df = df.groupby("a")
151+
152+
result = groupby_df.sample()
153+
expected = df
154+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)