Skip to content

Commit c5560a5

Browse files
committed
Only apply first row once in fast apply
1 parent 2626215 commit c5560a5

File tree

2 files changed

+15
-16
lines changed

2 files changed

+15
-16
lines changed

pandas/_libs/reduction.pyx

+14-15
Original file line numberDiff line numberDiff line change
@@ -507,17 +507,6 @@ def apply_frame_axis0(object frame, object f, object names,
507507

508508
results = []
509509

510-
# Need to infer if our low-level mucking is going to cause a segfault
511-
if n > 0:
512-
chunk = frame.iloc[starts[0]:ends[0]]
513-
object.__setattr__(chunk, 'name', names[0])
514-
try:
515-
result = f(chunk)
516-
if result is chunk:
517-
raise InvalidApply('Function unsafe for fast apply')
518-
except:
519-
raise InvalidApply('Let this error raise above us')
520-
521510
slider = BlockSlider(frame)
522511

523512
mutated = False
@@ -527,13 +516,23 @@ def apply_frame_axis0(object frame, object f, object names,
527516
slider.move(starts[i], ends[i])
528517

529518
item_cache.clear() # ugh
530-
531-
object.__setattr__(slider.dummy, 'name', names[i])
532-
piece = f(slider.dummy)
519+
chunk = slider.dummy
520+
object.__setattr__(chunk, 'name', names[i])
521+
522+
# Need to infer if our low-level mucking will cause a segfault
523+
if i == 0:
524+
try:
525+
piece = f(chunk)
526+
if piece is chunk:
527+
raise InvalidApply('Function unsafe for fast apply')
528+
except:
529+
raise InvalidApply('Let this error raise above us')
530+
else:
531+
piece = f(chunk)
533532

534533
# I'm paying the price for index-sharing, ugh
535534
try:
536-
if piece.index is slider.dummy.index:
535+
if piece.index is chunk.index:
537536
piece = piece.copy(deep='all')
538537
else:
539538
mutated = True

pandas/tests/groupby/test_groupby.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1431,7 +1431,7 @@ def f(group):
14311431
df.groupby('a', sort=False, group_keys=False).apply(f)
14321432
# we expect 2 zeros because we call ``f`` once to see if a faster route
14331433
# can be used.
1434-
expected_names = [0, 0, 1, 2]
1434+
expected_names = [0, 1, 2]
14351435
assert names == expected_names
14361436

14371437

0 commit comments

Comments
 (0)