Skip to content

Commit d240554

Browse files
dsaxtonproost
authored andcommitted
BUG: Fix issue with apply on empty DataFrame (pandas-dev#28213)
1 parent 0f112ad commit d240554

File tree

3 files changed

+29
-5
lines changed

3 files changed

+29
-5
lines changed

doc/source/whatsnew/v1.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -244,8 +244,8 @@ Groupby/resample/rolling
244244
Reshaping
245245
^^^^^^^^^
246246

247+
- Bug in :meth:`DataFrame.apply` that caused incorrect output with empty :class:`DataFrame` (:issue:`28202`, :issue:`21959`)
247248
- Bug in :meth:`DataFrame.stack` not handling non-unique indexes correctly when creating MultiIndex (:issue: `28301`)
248-
-
249249

250250
Sparse
251251
^^^^^^

pandas/core/apply.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -204,17 +204,20 @@ def apply_empty_result(self):
204204
from pandas import Series
205205

206206
if not should_reduce:
207-
208-
EMPTY_SERIES = Series([])
209207
try:
210-
r = self.f(EMPTY_SERIES, *self.args, **self.kwds)
208+
r = self.f(Series([]))
211209
except Exception:
212210
pass
213211
else:
214212
should_reduce = not isinstance(r, Series)
215213

216214
if should_reduce:
217-
return self.obj._constructor_sliced(np.nan, index=self.agg_axis)
215+
if len(self.agg_axis):
216+
r = self.f(Series([]))
217+
else:
218+
r = np.nan
219+
220+
return self.obj._constructor_sliced(r, index=self.agg_axis)
218221
else:
219222
return self.obj.copy()
220223

pandas/tests/frame/test_apply.py

+21
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,27 @@ def test_apply_with_reduce_empty(self):
116116
# Ensure that x.append hasn't been called
117117
assert x == []
118118

119+
@pytest.mark.parametrize("func", ["sum", "prod", "any", "all"])
120+
def test_apply_funcs_over_empty(self, func):
121+
# GH 28213
122+
df = DataFrame(columns=["a", "b", "c"])
123+
124+
result = df.apply(getattr(np, func))
125+
expected = getattr(df, func)()
126+
assert_series_equal(result, expected)
127+
128+
def test_nunique_empty(self):
129+
# GH 28213
130+
df = DataFrame(columns=["a", "b", "c"])
131+
132+
result = df.nunique()
133+
expected = Series(0, index=df.columns)
134+
assert_series_equal(result, expected)
135+
136+
result = df.T.nunique()
137+
expected = Series([], index=pd.Index([]))
138+
assert_series_equal(result, expected)
139+
119140
def test_apply_deprecate_reduce(self):
120141
empty_frame = DataFrame()
121142

0 commit comments

Comments
 (0)