Equivalent to public method `where`, except that `other` is not applied as a function even if callable. Used in __setitem__.
(
self,
cond,
other=lib.no_default,
*,
inplace: bool = False,
axis: Axis | None = None,
level=None,
)
| 9968 | |
| 9969 | @final |
| 9970 | def _where( |
| 9971 | self, |
| 9972 | cond, |
| 9973 | other=lib.no_default, |
| 9974 | *, |
| 9975 | inplace: bool = False, |
| 9976 | axis: Axis | None = None, |
| 9977 | level=None, |
| 9978 | ) -> Self: |
| 9979 | """ |
| 9980 | Equivalent to public method `where`, except that `other` is not |
| 9981 | applied as a function even if callable. Used in __setitem__. |
| 9982 | """ |
| 9983 | inplace = validate_bool_kwarg(inplace, "inplace") |
| 9984 | |
| 9985 | if axis is not None: |
| 9986 | axis = self._get_axis_number(axis) |
| 9987 | |
| 9988 | # align the cond to same shape as myself |
| 9989 | cond = common.apply_if_callable(cond, self) |
| 9990 | if isinstance(cond, NDFrame): |
| 9991 | # CoW: Make sure reference is not kept alive |
| 9992 | if cond.ndim == 1 and self.ndim == 2: |
| 9993 | cond = cond._constructor_expanddim( |
| 9994 | dict.fromkeys(range(len(self.columns)), cond), |
| 9995 | copy=False, |
| 9996 | ) |
| 9997 | cond.columns = self.columns |
| 9998 | cond = cond.align(self, join="right")[0] |
| 9999 | else: |
| 10000 | if not hasattr(cond, "shape"): |
| 10001 | cond = np.asanyarray(cond) |
| 10002 | if cond.shape != self.shape: |
| 10003 | raise ValueError("Array conditional must be same shape as self") |
| 10004 | cond = self._constructor(cond, **self._construct_axes_dict(), copy=False) |
| 10005 | |
| 10006 | # make sure we are boolean |
| 10007 | fill_value = bool(inplace) |
| 10008 | cond = cond.fillna(fill_value) |
| 10009 | cond = cond.infer_objects() |
| 10010 | |
| 10011 | msg = "Boolean array expected for the condition, not {dtype}" |
| 10012 | |
| 10013 | if not cond.empty: |
| 10014 | if not isinstance(cond, ABCDataFrame): |
| 10015 | # This is a single-dimensional object. |
| 10016 | if not is_bool_dtype(cond): |
| 10017 | raise TypeError(msg.format(dtype=cond.dtype)) |
| 10018 | else: |
| 10019 | for block in cond._mgr.blocks: |
| 10020 | if not is_bool_dtype(block.dtype): |
| 10021 | raise TypeError(msg.format(dtype=block.dtype)) |
| 10022 | if cond._mgr.any_extension_types: |
| 10023 | # GH51574: avoid object ndarray conversion later on |
| 10024 | cond = cond._constructor( |
| 10025 | cond.to_numpy(dtype=bool, na_value=fill_value), |
| 10026 | **cond._construct_axes_dict(), |
| 10027 | ) |