Skip to content

Commit c40bf02

Browse files
authored
Bug 29764 groupby loses index name sometimes (#36121)
1 parent d0de0c6 commit c40bf02

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

doc/source/whatsnew/v1.2.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ Groupby/resample/rolling
312312
- Bug in :meth:`DataFrameGroupby.apply` would drop a :class:`CategoricalIndex` when grouped on. (:issue:`35792`)
313313
- Bug when subsetting columns on a :class:`~pandas.core.groupby.DataFrameGroupBy` (e.g. ``df.groupby('a')[['b']])``) would reset the attributes ``axis``, ``dropna``, ``group_keys``, ``level``, ``mutated``, ``sort``, and ``squeeze`` to their default values. (:issue:`9959`)
314314
- Bug in :meth:`DataFrameGroupby.tshift` failing to raise ``ValueError`` when a frequency cannot be inferred for the index of a group (:issue:`35937`)
315+
- Bug in :meth:`DataFrame.groupby` does not always maintain column index name for ``any``, ``all``, ``bfill``, ``ffill``, ``shift`` (:issue:`29764`)
315316
-
316317

317318
Reshaping

pandas/core/groupby/generic.py

+1
Original file line numberDiff line numberDiff line change
@@ -1695,6 +1695,7 @@ def _wrap_transformed_output(
16951695
"""
16961696
indexed_output = {key.position: val for key, val in output.items()}
16971697
columns = Index(key.label for key in output)
1698+
columns.name = self.obj.columns.name
16981699

16991700
result = self.obj._constructor(indexed_output)
17001701
result.columns = columns

pandas/tests/groupby/test_groupby.py

+23
Original file line numberDiff line numberDiff line change
@@ -2111,3 +2111,26 @@ def test_subsetting_columns_keeps_attrs(klass, attr, value):
21112111
expected = df.groupby("a", **{attr: value})
21122112
result = expected[["b"]] if klass is DataFrame else expected["b"]
21132113
assert getattr(result, attr) == getattr(expected, attr)
2114+
2115+
2116+
@pytest.mark.parametrize("func", ["sum", "any", "shift"])
2117+
def test_groupby_column_index_name_lost(func):
2118+
# GH: 29764 groupby loses index sometimes
2119+
expected = pd.Index(["a"], name="idx")
2120+
df = pd.DataFrame([[1]], columns=expected)
2121+
df_grouped = df.groupby([1])
2122+
result = getattr(df_grouped, func)().columns
2123+
tm.assert_index_equal(result, expected)
2124+
2125+
2126+
@pytest.mark.parametrize("func", ["ffill", "bfill"])
2127+
def test_groupby_column_index_name_lost_fill_funcs(func):
2128+
# GH: 29764 groupby loses index sometimes
2129+
df = pd.DataFrame(
2130+
[[1, 1.0, -1.0], [1, np.nan, np.nan], [1, 2.0, -2.0]],
2131+
columns=pd.Index(["type", "a", "b"], name="idx"),
2132+
)
2133+
df_grouped = df.groupby(["type"])[["a", "b"]]
2134+
result = getattr(df_grouped, func)().columns
2135+
expected = pd.Index(["a", "b"], name="idx")
2136+
tm.assert_index_equal(result, expected)

0 commit comments

Comments
 (0)