(
self,
func: Callable[..., Any],
name: str,
numeric_only: bool = False,
numba_args: tuple[Any, ...] = (),
**kwargs,
)
| 690 | super().__init__(obj, *args, **kwargs) |
| 691 | |
| 692 | def _apply( |
| 693 | self, |
| 694 | func: Callable[..., Any], |
| 695 | name: str, |
| 696 | numeric_only: bool = False, |
| 697 | numba_args: tuple[Any, ...] = (), |
| 698 | **kwargs, |
| 699 | ) -> DataFrame | Series: |
| 700 | result = super()._apply( |
| 701 | func, |
| 702 | name, |
| 703 | numeric_only, |
| 704 | numba_args, |
| 705 | **kwargs, |
| 706 | ) |
| 707 | # Reconstruct the resulting MultiIndex |
| 708 | # 1st set of levels = group by labels |
| 709 | # 2nd set of levels = original DataFrame/Series index |
| 710 | grouped_object_index = self.obj.index |
| 711 | grouped_index_name = [*grouped_object_index.names] |
| 712 | groupby_keys = copy.copy(self._grouper.names) |
| 713 | result_index_names = groupby_keys + grouped_index_name |
| 714 | |
| 715 | drop_columns = [ |
| 716 | key |
| 717 | for key in self._grouper.names |
| 718 | if key not in self.obj.index.names or key is None |
| 719 | ] |
| 720 | |
| 721 | if len(drop_columns) != len(groupby_keys): |
| 722 | # Our result will have still kept the column in the result |
| 723 | result = result.drop(columns=drop_columns, errors="ignore") |
| 724 | |
| 725 | codes = self._grouper.codes |
| 726 | levels = copy.copy(self._grouper.levels) |
| 727 | |
| 728 | group_indices = self._grouper.indices.values() |
| 729 | if group_indices: |
| 730 | indexer = np.concatenate(list(group_indices)) |
| 731 | else: |
| 732 | indexer = np.array([], dtype=np.intp) |
| 733 | codes = [c.take(indexer) for c in codes] |
| 734 | |
| 735 | # if the index of the original dataframe needs to be preserved, append |
| 736 | # this index (but reordered) to the codes/levels from the groupby |
| 737 | if grouped_object_index is not None: |
| 738 | idx = grouped_object_index.take(indexer) |
| 739 | if not isinstance(idx, MultiIndex): |
| 740 | idx = MultiIndex.from_arrays([idx]) |
| 741 | codes.extend(list(idx.codes)) |
| 742 | levels.extend(list(idx.levels)) |
| 743 | |
| 744 | result_index = MultiIndex( |
| 745 | levels, codes, names=result_index_names, verify_integrity=False |
| 746 | ) |
| 747 | |
| 748 | result.index = result_index |
| 749 | if not self._as_index: |
nothing calls this directly
no test coverage detected