Skip to content

BUG: fix empty groupby(..., as_index=False).apply(...) index name inconsistency#65332

Open
Ashish-ml-eng wants to merge 2 commits intopandas-dev:mainfrom
Ashish-ml-eng:bug/as-index-false-empty-apply-index-name
Open

BUG: fix empty groupby(..., as_index=False).apply(...) index name inconsistency#65332
Ashish-ml-eng wants to merge 2 commits intopandas-dev:mainfrom
Ashish-ml-eng:bug/as-index-false-empty-apply-index-name

Conversation

@Ashish-ml-eng
Copy link
Copy Markdown

Closes #48135

What happened

DataFrame.groupby(..., as_index=False).apply(...) behaved differently for empty vs non-empty input:

  • non-empty input -> result.index.names == [None]
  • empty input -> result.index.names == ['A'] (group key name)

What this PR changes

In the empty-values path of DataFrameGroupBy._wrap_applied_output
(pandas/core/groupby/generic.py), this PR makes as_index=False use
res_index = None instead of self._grouper.result_index.

This keeps empty-output behavior consistent with non-empty output when
as_index=False.

Tests

Added a regression test in pandas/tests/groupby/test_apply.py that checks:

  • non-empty case index names are [None]
  • empty case index names match the non-empty case

Copilot AI review requested due to automatic review settings April 22, 2026 08:56
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Fixes an inconsistency in DataFrame.groupby(..., as_index=False).apply(...) where empty inputs previously produced an index with the group key name (e.g. ['A']), while non-empty inputs produced unnamed index levels ([None]).

Changes:

  • Adjust DataFrameGroupBy._wrap_applied_output empty-values handling to set res_index=None when as_index=False.
  • Add a regression test asserting index name parity between empty and non-empty groupby(..., as_index=False).apply(...).

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
pandas/core/groupby/generic.py Aligns empty-apply index construction with the non-empty as_index=False behavior by avoiding result_index in the empty path.
pandas/tests/groupby/test_apply.py Adds coverage to ensure empty and non-empty results have consistent index.names when as_index=False.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pandas/tests/groupby/test_apply.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: The parameter “as_index=False” is not valid when the source DataFrame is empty

2 participants