Skip to content

Commit a000ca9

Browse files
authored
ENH: Raise when subsetting columns on groupby with axis=1 (#37727)
* ENH: Raise when subsetting columns on groupby with axis=1 * whatsnew
1 parent ee1b75c commit a000ca9

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

doc/source/whatsnew/v1.2.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ Other enhancements
233233
- :func:`read_csv` supports memory-mapping for compressed files (:issue:`37621`)
234234
- Improve error reporting for :meth:`DataFrame.merge()` when invalid merge column definitions were given (:issue:`16228`)
235235
- Improve numerical stability for :meth:`Rolling.skew()`, :meth:`Rolling.kurt()`, :meth:`Expanding.skew()` and :meth:`Expanding.kurt()` through implementation of Kahan summation (:issue:`6929`)
236+
- Improved error reporting for subsetting columns of a :class:`DataFrameGroupBy` with ``axis=1`` (:issue:`37725`)
236237

237238
.. _whatsnew_120.api_breaking.python:
238239

pandas/core/groupby/generic.py

+3
Original file line numberDiff line numberDiff line change
@@ -1530,6 +1530,9 @@ def filter(self, func, dropna=True, *args, **kwargs):
15301530
return self._apply_filter(indices, dropna)
15311531

15321532
def __getitem__(self, key):
1533+
if self.axis == 1:
1534+
# GH 37725
1535+
raise ValueError("Cannot subset columns when using axis=1")
15331536
# per GH 23566
15341537
if isinstance(key, tuple) and len(key) > 1:
15351538
# if len == 1, then it becomes a SeriesGroupBy and this is actually

pandas/tests/groupby/test_groupby.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -2081,7 +2081,6 @@ def test_group_on_two_row_multiindex_returns_one_tuple_key():
20812081
@pytest.mark.parametrize(
20822082
"klass, attr, value",
20832083
[
2084-
(DataFrame, "axis", 1),
20852084
(DataFrame, "level", "a"),
20862085
(DataFrame, "as_index", False),
20872086
(DataFrame, "sort", False),
@@ -2120,6 +2119,14 @@ def test_subsetting_columns_keeps_attrs(klass, attr, value):
21202119
assert getattr(result, attr) == getattr(expected, attr)
21212120

21222121

2122+
def test_subsetting_columns_axis_1():
2123+
# GH 37725
2124+
g = DataFrame({"A": [1], "B": [2], "C": [3]}).groupby([0, 0, 1], axis=1)
2125+
match = "Cannot subset columns when using axis=1"
2126+
with pytest.raises(ValueError, match=match):
2127+
g[["A", "B"]].sum()
2128+
2129+
21232130
@pytest.mark.parametrize("func", ["sum", "any", "shift"])
21242131
def test_groupby_column_index_name_lost(func):
21252132
# GH: 29764 groupby loses index sometimes

0 commit comments

Comments
 (0)