forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapply.py
1978 lines (1634 loc) · 62.6 KB
/
apply.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import abc
from collections import defaultdict
import functools
from functools import partial
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Literal,
cast,
)
import numpy as np
from pandas._libs.internals import BlockValuesRefs
from pandas._typing import (
AggFuncType,
AggFuncTypeBase,
AggFuncTypeDict,
AggObjType,
Axis,
AxisInt,
NDFrameT,
npt,
)
from pandas.compat._optional import import_optional_dependency
from pandas.errors import SpecificationError
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.cast import is_nested_object
from pandas.core.dtypes.common import (
is_dict_like,
is_extension_array_dtype,
is_list_like,
is_numeric_dtype,
is_sequence,
)
from pandas.core.dtypes.dtypes import (
CategoricalDtype,
ExtensionDtype,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCNDFrame,
ABCSeries,
)
from pandas.core._numba.executor import generate_apply_looper
import pandas.core.common as com
from pandas.core.construction import ensure_wrapped_if_datetimelike
if TYPE_CHECKING:
from collections.abc import (
Generator,
Hashable,
Iterable,
MutableMapping,
Sequence,
)
from pandas import (
DataFrame,
Index,
Series,
)
from pandas.core.groupby import GroupBy
from pandas.core.resample import Resampler
from pandas.core.window.rolling import BaseWindow
ResType = dict[int, Any]
def frame_apply(
obj: DataFrame,
func: AggFuncType,
axis: Axis = 0,
raw: bool = False,
result_type: str | None = None,
by_row: Literal[False, "compat"] = "compat",
engine: str = "python",
engine_kwargs: dict[str, bool] | None = None,
args=None,
kwargs=None,
) -> FrameApply:
"""construct and return a row or column based frame apply object"""
axis = obj._get_axis_number(axis)
klass: type[FrameApply]
if axis == 0:
klass = FrameRowApply
elif axis == 1:
klass = FrameColumnApply
_, func, _, _ = reconstruct_func(func, **kwargs)
assert func is not None
return klass(
obj,
func,
raw=raw,
result_type=result_type,
by_row=by_row,
engine=engine,
engine_kwargs=engine_kwargs,
args=args,
kwargs=kwargs,
)
class Apply(metaclass=abc.ABCMeta):
axis: AxisInt
def __init__(
self,
obj: AggObjType,
func: AggFuncType,
raw: bool,
result_type: str | None,
*,
by_row: Literal[False, "compat", "_compat"] = "compat",
engine: str = "python",
engine_kwargs: dict[str, bool] | None = None,
args,
kwargs,
) -> None:
self.obj = obj
self.raw = raw
assert by_row is False or by_row in ["compat", "_compat"]
self.by_row = by_row
self.args = args or ()
self.kwargs = kwargs or {}
self.engine = engine
self.engine_kwargs = {} if engine_kwargs is None else engine_kwargs
if result_type not in [None, "reduce", "broadcast", "expand"]:
raise ValueError(
"invalid value for result_type, must be one "
"of {None, 'reduce', 'broadcast', 'expand'}"
)
self.result_type = result_type
self.func = func
@abc.abstractmethod
def apply(self) -> DataFrame | Series:
pass
@abc.abstractmethod
def agg_or_apply_list_like(
self, op_name: Literal["agg", "apply"]
) -> DataFrame | Series:
pass
@abc.abstractmethod
def agg_or_apply_dict_like(
self, op_name: Literal["agg", "apply"]
) -> DataFrame | Series:
pass
def agg(self) -> DataFrame | Series | None:
"""
Provide an implementation for the aggregators.
Returns
-------
Result of aggregation, or None if agg cannot be performed by
this method.
"""
func = self.func
if isinstance(func, str):
return self.apply_str()
if is_dict_like(func):
return self.agg_dict_like()
elif is_list_like(func):
# we require a list, but not a 'str'
return self.agg_list_like()
# caller can react
return None
def transform(self) -> DataFrame | Series:
"""
Transform a DataFrame or Series.
Returns
-------
DataFrame or Series
Result of applying ``func`` along the given axis of the
Series or DataFrame.
Raises
------
ValueError
If the transform function fails or does not transform.
"""
obj = self.obj
func = self.func
axis = self.axis
args = self.args
kwargs = self.kwargs
is_series = obj.ndim == 1
if obj._get_axis_number(axis) == 1:
assert not is_series
return obj.T.transform(func, 0, *args, **kwargs).T
if is_list_like(func) and not is_dict_like(func):
func = cast(list[AggFuncTypeBase], func)
# Convert func equivalent dict
if is_series:
func = {com.get_callable_name(v) or v: v for v in func}
else:
func = {col: func for col in obj}
if is_dict_like(func):
func = cast(AggFuncTypeDict, func)
return self.transform_dict_like(func)
# func is either str or callable
func = cast(AggFuncTypeBase, func)
try:
result = self.transform_str_or_callable(func)
except TypeError:
raise
except Exception as err:
raise ValueError("Transform function failed") from err
# Functions that transform may return empty Series/DataFrame
# when the dtype is not appropriate
if (
isinstance(result, (ABCSeries, ABCDataFrame))
and result.empty
and not obj.empty
):
raise ValueError("Transform function failed")
# error: Argument 1 to "__get__" of "AxisProperty" has incompatible type
# "Union[Series, DataFrame, GroupBy[Any], SeriesGroupBy,
# DataFrameGroupBy, BaseWindow, Resampler]"; expected "Union[DataFrame,
# Series]"
if not isinstance(result, (ABCSeries, ABCDataFrame)) or not result.index.equals(
obj.index # type: ignore[arg-type]
):
raise ValueError("Function did not transform")
return result
def transform_dict_like(self, func) -> DataFrame:
"""
Compute transform in the case of a dict-like func
"""
from pandas.core.reshape.concat import concat
obj = self.obj
args = self.args
kwargs = self.kwargs
# transform is currently only for Series/DataFrame
assert isinstance(obj, ABCNDFrame)
if len(func) == 0:
raise ValueError("No transform functions were provided")
func = self.normalize_dictlike_arg("transform", obj, func)
results: dict[Hashable, DataFrame | Series] = {}
for name, how in func.items():
colg = obj._gotitem(name, ndim=1)
results[name] = colg.transform(how, 0, *args, **kwargs)
return concat(results, axis=1)
def transform_str_or_callable(self, func) -> DataFrame | Series:
"""
Compute transform in the case of a string or callable func
"""
obj = self.obj
args = self.args
kwargs = self.kwargs
if isinstance(func, str):
return self._apply_str(obj, func, *args, **kwargs)
# Two possible ways to use a UDF - apply or call directly
try:
return obj.apply(func, args=args, **kwargs)
except Exception:
return func(obj, *args, **kwargs)
def agg_list_like(self) -> DataFrame | Series:
"""
Compute aggregation in the case of a list-like argument.
Returns
-------
Result of aggregation.
"""
kwargs = self.kwargs
return self.agg_or_apply_list_like(op_name="agg", **kwargs)
def compute_list_like(
self,
op_name: Literal["agg", "apply"],
selected_obj: Series | DataFrame,
**kwargs: dict[str, Any],
) -> tuple[list[Hashable] | Index, list[Any]]:
"""
Compute agg/apply results for like-like input.
Parameters
----------
op_name : {"agg", "apply"}
Operation being performed.
selected_obj : Series or DataFrame
Data to perform operation on.
kwargs : dict
Keyword arguments to pass to the functions.
Returns
-------
keys : list[Hashable] or Index
Index labels for result.
results : list
Data for result. When aggregating with a Series, this can contain any
Python objects.
"""
func = cast(list[AggFuncTypeBase], self.func)
obj = self.obj
results = []
keys = []
# degenerate case
if selected_obj.ndim == 1:
for a in func:
colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj)
args = (
[self.axis, *self.args]
if include_axis(op_name, colg)
else self.args
)
new_res = getattr(colg, op_name)(a, *args, **kwargs)
results.append(new_res)
# make sure we find a good name
name = com.get_callable_name(a) or a
keys.append(name)
else:
indices = []
for index, col in enumerate(selected_obj):
colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index])
args = (
[self.axis, *self.args]
if include_axis(op_name, colg)
else self.args
)
new_res = getattr(colg, op_name)(func, *args, **kwargs)
results.append(new_res)
indices.append(index)
# error: Incompatible types in assignment (expression has type "Any |
# Index", variable has type "list[Any | Callable[..., Any] | str]")
keys = selected_obj.columns.take(indices) # type: ignore[assignment]
return keys, results
def wrap_results_list_like(
self, keys: Iterable[Hashable], results: list[Series | DataFrame]
):
from pandas.core.reshape.concat import concat
obj = self.obj
try:
return concat(results, keys=keys, axis=1, sort=False)
except TypeError as err:
# we are concatting non-NDFrame objects,
# e.g. a list of scalars
from pandas import Series
result = Series(results, index=keys, name=obj.name)
if is_nested_object(result):
raise ValueError(
"cannot combine transform and aggregation operations"
) from err
return result
def agg_dict_like(self) -> DataFrame | Series:
"""
Compute aggregation in the case of a dict-like argument.
Returns
-------
Result of aggregation.
"""
return self.agg_or_apply_dict_like(op_name="agg")
def compute_dict_like(
self,
op_name: Literal["agg", "apply"],
selected_obj: Series | DataFrame,
selection: Hashable | Sequence[Hashable],
kwargs: dict[str, Any],
) -> tuple[list[Hashable], list[Any]]:
"""
Compute agg/apply results for dict-like input.
Parameters
----------
op_name : {"agg", "apply"}
Operation being performed.
selected_obj : Series or DataFrame
Data to perform operation on.
selection : hashable or sequence of hashables
Used by GroupBy, Window, and Resample if selection is applied to the object.
kwargs : dict
Keyword arguments to pass to the functions.
Returns
-------
keys : list[hashable]
Index labels for result.
results : list
Data for result. When aggregating with a Series, this can contain any
Python object.
"""
from pandas.core.groupby.generic import (
DataFrameGroupBy,
SeriesGroupBy,
)
obj = self.obj
is_groupby = isinstance(obj, (DataFrameGroupBy, SeriesGroupBy))
func = cast(AggFuncTypeDict, self.func)
func = self.normalize_dictlike_arg(op_name, selected_obj, func)
is_non_unique_col = (
selected_obj.ndim == 2
and selected_obj.columns.nunique() < len(selected_obj.columns)
)
if selected_obj.ndim == 1:
# key only used for output
colg = obj._gotitem(selection, ndim=1)
results = [getattr(colg, op_name)(how, **kwargs) for _, how in func.items()]
keys = list(func.keys())
elif not is_groupby and is_non_unique_col:
# key used for column selection and output
# GH#51099
results = []
keys = []
for key, how in func.items():
indices = selected_obj.columns.get_indexer_for([key])
labels = selected_obj.columns.take(indices)
label_to_indices = defaultdict(list)
for index, label in zip(indices, labels):
label_to_indices[label].append(index)
key_data = [
getattr(selected_obj._ixs(indice, axis=1), op_name)(how, **kwargs)
for label, indices in label_to_indices.items()
for indice in indices
]
keys += [key] * len(key_data)
results += key_data
else:
# key used for column selection and output
results = [
getattr(obj._gotitem(key, ndim=1), op_name)(how, **kwargs)
for key, how in func.items()
]
keys = list(func.keys())
return keys, results
def wrap_results_dict_like(
self,
selected_obj: Series | DataFrame,
result_index: list[Hashable],
result_data: list,
):
from pandas import Index
from pandas.core.reshape.concat import concat
obj = self.obj
# Avoid making two isinstance calls in all and any below
is_ndframe = [isinstance(r, ABCNDFrame) for r in result_data]
if all(is_ndframe):
results = dict(zip(result_index, result_data))
keys_to_use: Iterable[Hashable]
keys_to_use = [k for k in result_index if not results[k].empty]
# Have to check, if at least one DataFrame is not empty.
keys_to_use = keys_to_use if keys_to_use != [] else result_index
if selected_obj.ndim == 2:
# keys are columns, so we can preserve names
ktu = Index(keys_to_use)
ktu._set_names(selected_obj.columns.names)
keys_to_use = ktu
axis: AxisInt = 0 if isinstance(obj, ABCSeries) else 1
result = concat(
{k: results[k] for k in keys_to_use},
axis=axis,
keys=keys_to_use,
)
elif any(is_ndframe):
# There is a mix of NDFrames and scalars
raise ValueError(
"cannot perform both aggregation "
"and transformation operations "
"simultaneously"
)
else:
from pandas import Series
# we have a list of scalars
# GH 36212 use name only if obj is a series
if obj.ndim == 1:
obj = cast("Series", obj)
name = obj.name
else:
name = None
result = Series(result_data, index=result_index, name=name)
return result
def apply_str(self) -> DataFrame | Series:
"""
Compute apply in case of a string.
Returns
-------
result: Series or DataFrame
"""
# Caller is responsible for checking isinstance(self.f, str)
func = cast(str, self.func)
obj = self.obj
from pandas.core.groupby.generic import (
DataFrameGroupBy,
SeriesGroupBy,
)
# Support for `frame.transform('method')`
# Some methods (shift, etc.) require the axis argument, others
# don't, so inspect and insert if necessary.
method = getattr(obj, func, None)
if callable(method):
sig = inspect.getfullargspec(method)
arg_names = (*sig.args, *sig.kwonlyargs)
if self.axis != 0 and (
"axis" not in arg_names or func in ("corrwith", "skew")
):
raise ValueError(f"Operation {func} does not support axis=1")
if "axis" in arg_names and not isinstance(
obj, (SeriesGroupBy, DataFrameGroupBy)
):
self.kwargs["axis"] = self.axis
return self._apply_str(obj, func, *self.args, **self.kwargs)
def apply_list_or_dict_like(self) -> DataFrame | Series:
"""
Compute apply in case of a list-like or dict-like.
Returns
-------
result: Series, DataFrame, or None
Result when self.func is a list-like or dict-like, None otherwise.
"""
if self.engine == "numba":
raise NotImplementedError(
"The 'numba' engine doesn't support list-like/"
"dict likes of callables yet."
)
if self.axis == 1 and isinstance(self.obj, ABCDataFrame):
return self.obj.T.apply(self.func, 0, args=self.args, **self.kwargs).T
func = self.func
kwargs = self.kwargs
if is_dict_like(func):
result = self.agg_or_apply_dict_like(op_name="apply")
else:
result = self.agg_or_apply_list_like(op_name="apply")
result = reconstruct_and_relabel_result(result, func, **kwargs)
return result
def normalize_dictlike_arg(
self, how: str, obj: DataFrame | Series, func: AggFuncTypeDict
) -> AggFuncTypeDict:
"""
Handler for dict-like argument.
Ensures that necessary columns exist if obj is a DataFrame, and
that a nested renamer is not passed. Also normalizes to all lists
when values consists of a mix of list and non-lists.
"""
assert how in ("apply", "agg", "transform")
# Can't use func.values(); wouldn't work for a Series
if (
how == "agg"
and isinstance(obj, ABCSeries)
and any(is_list_like(v) for _, v in func.items())
) or (any(is_dict_like(v) for _, v in func.items())):
# GH 15931 - deprecation of renaming keys
raise SpecificationError("nested renamer is not supported")
if obj.ndim != 1:
# Check for missing columns on a frame
from pandas import Index
cols = Index(list(func.keys())).difference(obj.columns, sort=True)
if len(cols) > 0:
raise KeyError(f"Column(s) {list(cols)} do not exist")
aggregator_types = (list, tuple, dict)
# if we have a dict of any non-scalars
# eg. {'A' : ['mean']}, normalize all to
# be list-likes
# Cannot use func.values() because arg may be a Series
if any(isinstance(x, aggregator_types) for _, x in func.items()):
new_func: AggFuncTypeDict = {}
for k, v in func.items():
if not isinstance(v, aggregator_types):
new_func[k] = [v]
else:
new_func[k] = v
func = new_func
return func
def _apply_str(self, obj, func: str, *args, **kwargs):
"""
if arg is a string, then try to operate on it:
- try to find a function (or attribute) on obj
- try to find a numpy function
- raise
"""
assert isinstance(func, str)
if hasattr(obj, func):
f = getattr(obj, func)
if callable(f):
return f(*args, **kwargs)
# people may aggregate on a non-callable attribute
# but don't let them think they can pass args to it
assert len(args) == 0
assert len([kwarg for kwarg in kwargs if kwarg not in ["axis"]]) == 0
return f
elif hasattr(np, func) and hasattr(obj, "__array__"):
# in particular exclude Window
f = getattr(np, func)
return f(obj, *args, **kwargs)
else:
msg = f"'{func}' is not a valid function for '{type(obj).__name__}' object"
raise AttributeError(msg)
class NDFrameApply(Apply):
"""
Methods shared by FrameApply and SeriesApply but
not GroupByApply or ResamplerWindowApply
"""
obj: DataFrame | Series
@property
def index(self) -> Index:
return self.obj.index
@property
def agg_axis(self) -> Index:
return self.obj._get_agg_axis(self.axis)
def agg_or_apply_list_like(
self, op_name: Literal["agg", "apply"], numeric_only=False, **kwargs
) -> DataFrame | Series:
obj = self.obj
if op_name == "apply":
if isinstance(self, FrameApply):
by_row = self.by_row
elif isinstance(self, SeriesApply):
by_row = "_compat" if self.by_row else False
else:
by_row = False
kwargs = {**kwargs, "by_row": by_row}
if getattr(obj, "axis", 0) == 1:
raise NotImplementedError("axis other than 0 is not supported")
keys, results = self.compute_list_like(op_name, obj, **kwargs)
result = self.wrap_results_list_like(keys, results)
return result
def agg_or_apply_dict_like(
self, op_name: Literal["agg", "apply"]
) -> DataFrame | Series:
assert op_name in ["agg", "apply"]
obj = self.obj
kwargs = {}
if op_name == "apply":
by_row = "_compat" if self.by_row else False
kwargs.update({"by_row": by_row})
if getattr(obj, "axis", 0) == 1:
raise NotImplementedError("axis other than 0 is not supported")
selection = None
result_index, result_data = self.compute_dict_like(
op_name, obj, selection, kwargs
)
result = self.wrap_results_dict_like(obj, result_index, result_data)
return result
class FrameApply(NDFrameApply):
obj: DataFrame
def __init__(
self,
obj: AggObjType,
func: AggFuncType,
raw: bool,
result_type: str | None,
*,
by_row: Literal[False, "compat"] = False,
engine: str = "python",
engine_kwargs: dict[str, bool] | None = None,
args,
kwargs,
) -> None:
if by_row is not False and by_row != "compat":
raise ValueError(f"by_row={by_row} not allowed")
super().__init__(
obj,
func,
raw,
result_type,
by_row=by_row,
engine=engine,
engine_kwargs=engine_kwargs,
args=args,
kwargs=kwargs,
)
# ---------------------------------------------------------------
# Abstract Methods
@property
@abc.abstractmethod
def result_index(self) -> Index:
pass
@property
@abc.abstractmethod
def result_columns(self) -> Index:
pass
@property
@abc.abstractmethod
def series_generator(self) -> Generator[Series, None, None]:
pass
@staticmethod
@functools.cache
@abc.abstractmethod
def generate_numba_apply_func(
func, nogil=True, nopython=True, parallel=False
) -> Callable[[npt.NDArray, Index, Index], dict[int, Any]]:
pass
@abc.abstractmethod
def apply_with_numba(self):
pass
def validate_values_for_numba(self) -> None:
# Validate column dtyps all OK
for colname, dtype in self.obj.dtypes.items():
if not is_numeric_dtype(dtype):
raise ValueError(
f"Column {colname} must have a numeric dtype. "
f"Found '{dtype}' instead"
)
if is_extension_array_dtype(dtype):
raise ValueError(
f"Column {colname} is backed by an extension array, "
f"which is not supported by the numba engine."
)
@abc.abstractmethod
def wrap_results_for_axis(
self, results: ResType, res_index: Index
) -> DataFrame | Series:
pass
# ---------------------------------------------------------------
@property
def res_columns(self) -> Index:
return self.result_columns
@property
def columns(self) -> Index:
return self.obj.columns
@cache_readonly
def values(self):
return self.obj.values
def apply(self) -> DataFrame | Series:
"""compute the results"""
# dispatch to handle list-like or dict-like
if is_list_like(self.func):
if self.engine == "numba":
raise NotImplementedError(
"the 'numba' engine doesn't support lists of callables yet"
)
return self.apply_list_or_dict_like()
# all empty
if len(self.columns) == 0 and len(self.index) == 0:
return self.apply_empty_result()
# string dispatch
if isinstance(self.func, str):
if self.engine == "numba":
raise NotImplementedError(
"the 'numba' engine doesn't support using "
"a string as the callable function"
)
return self.apply_str()
# ufunc
elif isinstance(self.func, np.ufunc):
if self.engine == "numba":
raise NotImplementedError(
"the 'numba' engine doesn't support "
"using a numpy ufunc as the callable function"
)
with np.errstate(all="ignore"):
results = self.obj._mgr.apply("apply", func=self.func)
# _constructor will retain self.index and self.columns
return self.obj._constructor_from_mgr(results, axes=results.axes)
# broadcasting
if self.result_type == "broadcast":
if self.engine == "numba":
raise NotImplementedError(
"the 'numba' engine doesn't support result_type='broadcast'"
)
return self.apply_broadcast(self.obj)
# one axis empty
elif not all(self.obj.shape):
return self.apply_empty_result()
# raw
elif self.raw:
return self.apply_raw(engine=self.engine, engine_kwargs=self.engine_kwargs)
return self.apply_standard()
def agg(self):
obj = self.obj
axis = self.axis
# TODO: Avoid having to change state
self.obj = self.obj if self.axis == 0 else self.obj.T
self.axis = 0
result = None
try:
result = super().agg()
finally:
self.obj = obj
self.axis = axis
if axis == 1:
result = result.T if result is not None else result
if result is None:
result = self.obj.apply(self.func, axis, args=self.args, **self.kwargs)
return result
def apply_empty_result(self):
"""
we have an empty result; at least 1 axis is 0
we will try to apply the function to an empty
series in order to see if this is a reduction function
"""
assert callable(self.func)
# we are not asked to reduce or infer reduction
# so just return a copy of the existing object
if self.result_type not in ["reduce", None]:
return self.obj.copy()
# we may need to infer
should_reduce = self.result_type == "reduce"
from pandas import Series
if not should_reduce:
try:
if self.axis == 0:
r = self.func(
Series([], dtype=np.float64), *self.args, **self.kwargs
)
else:
r = self.func(
Series(index=self.columns, dtype=np.float64),
*self.args,
**self.kwargs,
)
except Exception:
pass
else:
should_reduce = not isinstance(r, Series)
if should_reduce:
if len(self.agg_axis):
r = self.func(Series([], dtype=np.float64), *self.args, **self.kwargs)
else:
r = np.nan
return self.obj._constructor_sliced(r, index=self.agg_axis)
else:
return self.obj.copy()
def apply_raw(self, engine="python", engine_kwargs=None):
"""apply to the values as a numpy array"""
def wrap_function(func):
"""
Wrap user supplied function to work around numpy issue.
see https://github.com/numpy/numpy/issues/8352
"""
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
if isinstance(result, str):
result = np.array(result, dtype=object)
return result
return wrapper
if engine == "numba":
engine_kwargs = {} if engine_kwargs is None else engine_kwargs
# error: Argument 1 to "__call__" of "_lru_cache_wrapper" has
# incompatible type "Callable[..., Any] | str | list[Callable
# [..., Any] | str] | dict[Hashable,Callable[..., Any] | str |
# list[Callable[..., Any] | str]]"; expected "Hashable"
nb_looper = generate_apply_looper(
self.func, # type: ignore[arg-type]
**engine_kwargs,
)
result = nb_looper(self.values, self.axis)
# If we made the result 2-D, squeeze it back to 1-D
result = np.squeeze(result)
else:
result = np.apply_along_axis(
wrap_function(self.func),
self.axis,
self.values,
*self.args,
**self.kwargs,
)
# TODO: mixed type case
if result.ndim == 2:
return self.obj._constructor(result, index=self.index, columns=self.columns)
else:
return self.obj._constructor_sliced(result, index=self.agg_axis)