-
-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Description
Code Sample, a copy-pastable example
import pandas as pd
df = pd.DataFrame({'a': (1, 2, 2)})
# The problem
df.groupby('a').apply(lambda x: None)
# The problem with a bit more context
df.groupby('a').apply(lambda group_df: 'foo' if len(group_df) > 0 else None)
df.groupby('a').apply(lambda group_df: 'foo' if len(group_df) > 1 else None)
df.groupby('a').apply(lambda group_df: 'foo' if len(group_df) > 2 else None)
Problem description
The first and last calls to apply in the above code each return an empty DataFrame.
Instead, they should behave like the other two calls to apply, i.e., return a Series that contains the values returned by the call to the lambda function on each group.
It seems to me that the trigger to the bug is that the applied function returns None for all groups.
Expected Output
>>> df.groupby('a').apply(lambda x: None) # The output is actually an empty df
a
1 None
2 None
>>> # The problem with a bit more context
>>> df.groupby('a').apply(lambda group_df: 'foo' if len(group_df) > 0 else None)
a
1 foo
2 foo
dtype: object
>>> df.groupby('a').apply(lambda group_df: 'foo' if len(group_df) > 1 else None)
a
1 None
2 foo
dtype: object
>>> df.groupby('a').apply(lambda group_df: 'foo' if len(group_df) > 2 else None) # The output is actually an empty df
a
1 None
2 None
Output of pd.show_versions()
INSTALLED VERSIONS
commit : None
python : 3.7.6.final.0
python-bits : 64
OS : Linux
OS-release : 4.15.0-101-generic
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8
pandas : 1.0.3
numpy : 1.18.1
pytz : 2020.1
dateutil : 2.8.1
pip : 20.0.2
setuptools : 46.4.0.post20200518
Cython : 0.29.17
pytest : 5.4.2
hypothesis : 5.11.0
sphinx : 3.0.3
blosc : None
feather : None
xlsxwriter : 1.2.8
lxml.etree : 4.5.0
html5lib : 1.0.1
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.13.0
pandas_datareader: None
bs4 : 4.9.0
bottleneck : 1.3.2
fastparquet : None
gcsfs : None
lxml.etree : 4.5.0
matplotlib : 3.1.3
numexpr : 2.7.1
odfpy : None
openpyxl : 3.0.3
pandas_gbq : None
pyarrow : None
pytables : None
pytest : 5.4.2
pyxlsb : None
s3fs : 0.4.2
scipy : 1.4.1
sqlalchemy : 1.3.17
tables : 3.6.1
tabulate : None
xarray : None
xlrd : 1.2.0
xlwt : 1.3.0
xlsxwriter : 1.2.8
numba : 0.49.1