MCPcopy
hub / github.com/pandas-dev/pandas / replace

Method replace

pandas/core/internals/blocks.py:675–739  ·  view source on GitHub ↗

replace the to_replace value with value, possible to create new blocks here this is just a call to putmask.

(
        self,
        to_replace,
        value,
        inplace: bool = False,
        # mask may be pre-computed if we're called from replace_list
        mask: npt.NDArray[np.bool_] | None = None,
    )

Source from the content-addressed store, hash-verified

673
674 @final
675 def replace(
676 self,
677 to_replace,
678 value,
679 inplace: bool = False,
680 # mask may be pre-computed if we're called from replace_list
681 mask: npt.NDArray[np.bool_] | None = None,
682 ) -> list[Block]:
683 """
684 replace the to_replace value with value, possible to create new
685 blocks here this is just a call to putmask.
686 """
687
688 # Note: the checks we do in NDFrame.replace ensure we never get
689 # here with listlike to_replace or value, as those cases
690 # go through replace_list
691 values = self.values
692
693 if not self._can_hold_element(to_replace):
694 # We cannot hold `to_replace`, so we know immediately that
695 # replacing it is a no-op.
696 # Note: If to_replace were a list, NDFrame.replace would call
697 # replace_list instead of replace.
698 return [self._maybe_copy(inplace, deep=False)]
699
700 if mask is None:
701 mask = missing.mask_missing(values, to_replace)
702 if not mask.any():
703 # Note: we get here with test_replace_extension_other incorrectly
704 # bc _can_hold_element is incorrect.
705 return [self._maybe_copy(inplace, deep=False)]
706
707 elif self._can_hold_element(value) or (self.dtype == "string" and is_re(value)):
708 # TODO(CoW): Maybe split here as well into columns where mask has True
709 # and rest?
710 blk = self._maybe_copy(inplace)
711 putmask_inplace(blk.values, mask, value)
712 return [blk]
713
714 elif self.ndim == 1 or self.shape[0] == 1:
715 if value is None or value is NA:
716 blk = self.astype(np.dtype(object))
717 else:
718 blk = self.coerce_to_target_dtype(value, raise_on_upcast=False)
719 return blk.replace(
720 to_replace=to_replace,
721 value=value,
722 inplace=True,
723 mask=mask,
724 )
725
726 else:
727 # split so that we only upcast where necessary
728 blocks = []
729 for i, nb in enumerate(self._split()):
730 blocks.extend(
731 type(self).replace(
732 nb,

Callers 13

_replace_coerceMethod · 0.95
make_flex_docFunction · 0.45
_str_replaceMethod · 0.45
_get_repr_footerMethod · 0.45
stdMethod · 0.45
_sub_datetimelikeMethod · 0.45
doc.pyFile · 0.45
melt_stubFunction · 0.45
local_nameMethod · 0.45
clean_column_nameFunction · 0.45

Calls 9

_can_hold_elementMethod · 0.95
_maybe_copyMethod · 0.95
astypeMethod · 0.95
_splitMethod · 0.95
is_reFunction · 0.90
putmask_inplaceFunction · 0.90
anyMethod · 0.45
dtypeMethod · 0.45

Tested by

no test coverage detected