Skip to content

BUG: df.groupby().apply() behaves inconsistently when there's only one group #54723

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
2 of 3 tasks
ypsah opened this issue Aug 24, 2023 · 2 comments
Closed
2 of 3 tasks
Labels
Apply Apply, Aggregate, Transform, Map Bug Duplicate Report Duplicate issue or pull request Groupby

Comments

@ypsah
Copy link

ypsah commented Aug 24, 2023

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd

PLAYERS = pd.DataFrame({
    "name": ["alice", "bob", "carol"],
    "team": "blue",
    "score": [10, 5, 12],
})

def _has_won(teammates: pd.DataFrame) -> pd.Series:
    """
    To win, one must score at least 6 and their team's average score must be >= 6
    """
    return (teammates["score"].mean() >= 6) & (teammates["score"] >= 6)

HAS_WON = PLAYERS.groupby(["team"], group_keys=False).apply(_has_won)
print(HAS_WON)

Issue Description

In the snippet above, HAS_WON has the wrong shape:

score     0      1     2
team                    
blue   True  False  True

This only happens when there's a single group in the dataframe.
Using:

PLAYERS = pd.DataFrame({
    "name": ["alice", "bob", "carol"],
    "team": ["blue", "red", "blue"],
    "score": [10, 5, 12],
})

The output becomes:

0     True
2     True
1    False
Name: score, dtype: bool

Expected Behavior

I would expect the reproducer I sent to produce a series whose shape does not depend on the number of groups.

At the moment, I work around the issue as follows:

teams = PLAYERS["team"].unique()
if len(teams) == 1:
    HAS_WON = _has_won(PLAYERS)
else:
    HAS_WON = PLAYERS.groupby(["team"], group_keys=False).apply(_has_won)

Installed Versions

INSTALLED VERSIONS

commit : 0f43794
python : 3.11.3.final.0
python-bits : 64
OS : Linux
OS-release : 6.4.11-arch2-1
Version : #1 SMP PREEMPT_DYNAMIC Sat, 19 Aug 2023 15:38:34 +0000
machine : x86_64
processor :
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 2.0.3
numpy : 1.25.2
pytz : 2023.3
dateutil : 2.8.2
setuptools : 68.0.0
pip : 23.1.2
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None

@ypsah ypsah added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 24, 2023
@ypsah
Copy link
Author

ypsah commented Aug 24, 2023

This feels related to #44803.

@rhshadrach
Copy link
Member

Duplicate of #42749. This particular operation should be performed without apply (breakup the operation and use .transform("mean") instead) - not only will you get better behavior, but it will be much faster too.

@rhshadrach rhshadrach added Groupby Duplicate Report Duplicate issue or pull request Apply Apply, Aggregate, Transform, Map and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Apply Apply, Aggregate, Transform, Map Bug Duplicate Report Duplicate issue or pull request Groupby
Projects
None yet
Development

No branches or pull requests

2 participants