Description
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
def return_series(x):
return pd.Series([x["A"] + x["B"]], index=x.index)
a_one = pd.DataFrame({"A": [1], "B": [2], "C": ["c"]})
a_two = pd.DataFrame({"A": [1, 2], "B": [2, 2], "C": ["c", "d"]})
res_one = a_one.groupby("C").apply(return_series) # Returns dataframe
res_two = a_two.groupby("C").apply(return_series) # Returns series
Issue Description
When using groupby.apply
with the same custom-function the end result is not consistent; it is either a series if there's multiple keys in the group-by or a dataframe if there's only one key value present.
Expected Behavior
It is understandable that some functions return either a series/dataframe depending on the function, but I would assume that the same function returns the same type i.e that the example above always returns either a dataframe or a series.
Installed Versions
INSTALLED VERSIONS
commit : ba1cccd
python : 3.11.4.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.22621
machine : AMD64
processor : Intel64 Family 6 Model 141 Stepping 1, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : Danish_Denmark.1252
pandas : 2.1.0
numpy : 1.24.1
pytz : 2023.3
dateutil : 2.8.2
setuptools : 65.5.0
pip : 23.1.2
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : 1.11.1
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : 1.1
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : None
pandas_datareader : None
bs4 : None
bottleneck : None
dataframe-api-compat: None
fastparquet : None
fsspec : 2023.6.0
gcsfs : None
matplotlib : 3.7.2
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : 0.19.2
pyarrow : 12.0.1
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.11.1
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None