@@ -726,6 +726,38 @@ def test_apply_noreduction_tzaware_object(self):
726
726
result = df .apply (lambda x : x .copy ())
727
727
tm .assert_frame_equal (result , df )
728
728
729
+ def test_apply_function_runs_once (self ):
730
+ # https://github.com/pandas-dev/pandas/issues/30815
731
+ def non_reducing_func_with_state (row ):
732
+ non_reducing_func_with_state .call_count = getattr (non_reducing_func_with_state , 'call_count' , 0 ) + 1
733
+ return row * non_reducing_func_with_state .call_count
734
+
735
+ def reducing_func_with_state (_ ):
736
+ reducing_func_with_state .call_count = getattr (reducing_func_with_state , 'call_count' , 0 ) + 1
737
+ return reducing_func_with_state .call_count
738
+
739
+ df = pd .DataFrame ({'a' : [1 , 2 , 3 ]})
740
+
741
+ # no reduction
742
+ res0 = df .apply (non_reducing_func_with_state )
743
+ tm .assert_frame_equal (res0 , df )
744
+
745
+ # reduction
746
+ res1 = df .apply (reducing_func_with_state )
747
+ tm .assert_series_equal (res1 , Series (data = [1 ], index = ['a' ]))
748
+
749
+ def test_applymap_function_runs_once (self ):
750
+
751
+ # This function will create the same values as in the DataFrame
752
+ def func_with_state (_ ):
753
+ func_with_state .call_count = getattr (func_with_state , 'call_count' , 0 ) + 1
754
+ return func_with_state .call_count
755
+
756
+ df = pd .DataFrame ({'a' : [1 , 2 , 3 ]})
757
+ result = df .applymap (func_with_state )
758
+ tm .assert_frame_equal (result , df )
759
+
760
+
729
761
730
762
class TestInferOutputShape :
731
763
# the user has supplied an opaque UDF where
0 commit comments