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
values = []
def my_fun(x):
values.append(x["a"])
empty_df = pd.DataFrame(columns=["a"])
empty_df.apply(my_fun, axis=1)
# >= 1.5.0 values contains [nan]
# < 1.5.0 values contains []
print(f"values contains {values}")
Issue Description
Prior to version 1.5.0, applying a function to an empty frame didn't apply the function. After some experiments with pandas 1.4.4, I discovered that the function is actually applied with an empty series as input, and access of the series values raised an exception that is caught and silenced. From a user perspective, it seemed like the function wasn't applied at all.
In 1.5.0 and 1.5.1, the function applied to an empty dataframe is applied with a series of NaN.
I'm not sure if this is actually a bug, but it's a recent change in behavior. I don't think this new behavior is what any user would expect. To me, the intuitive behavior would be that the function isn't executed at all.
Expected Behavior
import pandas as pd
values = []
def my_fun(x):
values.append(x["a"])
empty_df = pd.DataFrame(columns=["a"])
empty_df.apply(my_fun, axis=1)
assert not values
Installed Versions
INSTALLED VERSIONS
commit : 91111fd
python : 3.10.4.final.0
python-bits : 64
OS : Linux
OS-release : 4.15.0-194-generic
Version : #205-Ubuntu SMP Fri Sep 16 19:49:27 UTC 2022
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8
pandas : 1.5.1
numpy : 1.22.1
pytz : 2022.4
dateutil : 2.8.2
setuptools : 64.0.3
pip : 22.2.2
Cython : None
pytest : 7.1.2
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : 3.0.3
lxml.etree : 4.9.1
html5lib : 1.1
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.5.0
pandas_datareader: None
bs4 : 4.11.1
bottleneck : None
brotli : 1.0.9
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.6.0
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.8.1
snappy : None
sqlalchemy : None
tables : None
tabulate : 0.8.10
xarray : None
xlrd : None
xlwt : 1.3.0
zstandard : None
tzdata : None