Skip to content

ENH: Allow empty groupby #55068

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 6 commits 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/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Enhancements

.. _whatsnew_220.enhancements.enhancement1:

enhancement1
:class:`GroupBy` now accepts an empty list of ``keys`` and applies any aggregation over all the data (:issue:`35366`)
^^^^^^^^^^^^

.. _whatsnew_220.enhancements.enhancement2:
Expand Down
Binary file added doc/titanic.xlsx
Binary file not shown.
4 changes: 4 additions & 0 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1289,6 +1289,10 @@ def __init__(
dropna: bool = True,
) -> None:
self._selection = selection
# to resolve case when passed empty list
# didn't change self.keys directly to avoid side effects
# e.g. the use of get_grouper
keys = [np.int64(0)] * len(obj) if (iter(keys) and len(keys) == 0) else keys

assert isinstance(obj, NDFrame), type(obj)

Expand Down
56 changes: 56 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,62 @@
pytestmark = pytest.mark.filterwarnings("ignore:Mean of empty slice:RuntimeWarning")


def test_groupby_empty_list_keys():
# sample case of a series
s = Series([1, 2, 3])
# result = s.groupby([]).agg("min")
result = s.groupby([]).agg("min")
expected = Series([1])
tm.assert_series_equal(result, expected)
# sample case one column
df = DataFrame(
{
"group": ["A", "B", "A"],
"col": np.arange(3),
}
)
result_df = df.groupby([]).agg(col_min=("col", "min"))
expected_df = DataFrame([{"col_min": 0}])
tm.assert_frame_equal(result_df, expected_df)

# two columns in a datafram with other columns
df = DataFrame(
{
"group": ["A", "B", "A"],
"col1": np.arange(3),
"col2": np.arange(3, 6),
"col3": np.arange(6, 9),
}
)
result_df = df.groupby([]).agg(
col1_min=("col1", "min"),
col2_min=("col2", "sum"),
)
expected_df = DataFrame(
[{"col1_min": 0, "col2_min": 12}],
)
tm.assert_frame_equal(result_df, expected_df)

# std
result_df = df.groupby([]).agg(
col1_std=("col1", "std"),
)
expected_df = DataFrame(
[{"col1_std": 1.0}],
)
tm.assert_frame_equal(result_df, expected_df)

# different type of iterables
for key_iter in [np.array([]), (), set()]:
result_df = df.groupby(key_iter).agg(
col1_std=("col1", "std"),
)
expected_df = DataFrame(
[{"col1_std": 1.0}],
)
tm.assert_frame_equal(result_df, expected_df)


def test_repr():
# GH18203
result = repr(Grouper(key="A", level="B"))
Expand Down
5 changes: 0 additions & 5 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,11 +393,6 @@ def test_grouper_getting_correct_binner(self):
def test_grouper_iter(self, df):
assert sorted(df.groupby("A").grouper) == ["bar", "foo"]

def test_empty_groups(self, df):
# see gh-1048
with pytest.raises(ValueError, match="No group keys passed!"):
df.groupby([])

def test_groupby_grouper(self, df):
grouped = df.groupby("A")

Expand Down