|
2 | 2 | from datetime import datetime
|
3 | 3 | from itertools import chain
|
4 | 4 | import operator
|
| 5 | +from unittest.mock import Mock |
5 | 6 | import warnings
|
6 | 7 |
|
7 | 8 | import numpy as np
|
@@ -728,35 +729,25 @@ def test_apply_noreduction_tzaware_object(self):
|
728 | 729 |
|
729 | 730 | def test_apply_function_runs_once(self):
|
730 | 731 | # 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 |
| 732 | + non_reducing_mock = Mock(side_effect=lambda x: x) |
| 733 | + reducing_mock = Mock(return_value=1) |
734 | 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]}) |
| 735 | + df = pd.DataFrame({"a": [1, 2, 3]}) |
740 | 736 |
|
741 | 737 | # no reduction
|
742 |
| - res0 = df.apply(non_reducing_func_with_state) |
743 |
| - tm.assert_frame_equal(res0, df) |
| 738 | + df.apply(non_reducing_mock, axis=1) |
| 739 | + assert non_reducing_mock.call_count == 3 |
744 | 740 |
|
745 | 741 | # reduction
|
746 |
| - res1 = df.apply(reducing_func_with_state) |
747 |
| - tm.assert_series_equal(res1, Series(data=[1], index=['a'])) |
| 742 | + df.apply(reducing_mock, axis=1) |
| 743 | + assert reducing_mock.call_count == 3 |
748 | 744 |
|
749 | 745 | def test_applymap_function_runs_once(self):
|
| 746 | + reducing_mock = Mock(return_value=1) |
750 | 747 |
|
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 |
| - |
| 748 | + df = pd.DataFrame({"a": [1, 2, 3]}) |
| 749 | + df.applymap(reducing_mock) |
| 750 | + assert reducing_mock.call_count == 3 |
760 | 751 |
|
761 | 752 |
|
762 | 753 | class TestInferOutputShape:
|
|
0 commit comments