forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathblocks.py
2676 lines (2277 loc) · 90 KB
/
blocks.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
from functools import wraps
import re
from typing import (
TYPE_CHECKING,
Any,
Callable,
Literal,
cast,
final,
)
import warnings
import weakref
import numpy as np
from pandas._config import (
get_option,
using_copy_on_write,
)
from pandas._libs import (
NaT,
internals as libinternals,
lib,
writers,
)
from pandas._libs.internals import (
BlockPlacement,
BlockValuesRefs,
)
from pandas._libs.missing import NA
from pandas._typing import (
ArrayLike,
AxisInt,
DtypeObj,
F,
FillnaOptions,
IgnoreRaise,
InterpolateOptions,
QuantileInterpolation,
Self,
Shape,
npt,
)
from pandas.errors import AbstractMethodError
from pandas.util._decorators import cache_readonly
from pandas.util._exceptions import find_stack_level
from pandas.util._validators import validate_bool_kwarg
from pandas.core.dtypes.astype import (
astype_array_safe,
astype_is_view,
)
from pandas.core.dtypes.cast import (
LossySetitemError,
can_hold_element,
find_result_type,
maybe_downcast_to_dtype,
np_can_hold_element,
)
from pandas.core.dtypes.common import (
ensure_platform_int,
is_1d_only_ea_dtype,
is_float_dtype,
is_integer_dtype,
is_list_like,
is_scalar,
is_string_dtype,
)
from pandas.core.dtypes.dtypes import (
DatetimeTZDtype,
ExtensionDtype,
IntervalDtype,
NumpyEADtype,
PeriodDtype,
SparseDtype,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCIndex,
ABCNumpyExtensionArray,
ABCSeries,
)
from pandas.core.dtypes.missing import (
is_valid_na_for_dtype,
isna,
na_value_for_dtype,
)
from pandas.core import missing
import pandas.core.algorithms as algos
from pandas.core.array_algos.putmask import (
extract_bool_array,
putmask_inplace,
putmask_without_repeat,
setitem_datetimelike_compat,
validate_putmask,
)
from pandas.core.array_algos.quantile import quantile_compat
from pandas.core.array_algos.replace import (
compare_or_regex_search,
replace_regex,
should_use_regex,
)
from pandas.core.array_algos.transforms import shift
from pandas.core.arrays import (
Categorical,
DatetimeArray,
ExtensionArray,
IntervalArray,
NumpyExtensionArray,
PeriodArray,
TimedeltaArray,
)
from pandas.core.base import PandasObject
import pandas.core.common as com
from pandas.core.computation import expressions
from pandas.core.construction import (
ensure_wrapped_if_datetimelike,
extract_array,
)
from pandas.core.indexers import check_setitem_lengths
if TYPE_CHECKING:
from collections.abc import (
Iterable,
Sequence,
)
from pandas.core.api import Index
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
# comparison is faster than is_object_dtype
_dtype_obj = np.dtype("object")
def maybe_split(meth: F) -> F:
"""
If we have a multi-column block, split and operate block-wise. Otherwise
use the original method.
"""
@wraps(meth)
def newfunc(self, *args, **kwargs) -> list[Block]:
if self.ndim == 1 or self.shape[0] == 1:
return meth(self, *args, **kwargs)
else:
# Split and operate column-by-column
return self.split_and_operate(meth, *args, **kwargs)
return cast(F, newfunc)
class Block(PandasObject, libinternals.Block):
"""
Canonical n-dimensional unit of homogeneous dtype contained in a pandas
data structure
Index-ignorant; let the container take care of that
"""
values: np.ndarray | ExtensionArray
ndim: int
refs: BlockValuesRefs
__init__: Callable
__slots__ = ()
is_numeric = False
@final
@cache_readonly
def _validate_ndim(self) -> bool:
"""
We validate dimension for blocks that can hold 2D values, which for now
means numpy dtypes or DatetimeTZDtype.
"""
dtype = self.dtype
return not isinstance(dtype, ExtensionDtype) or isinstance(
dtype, DatetimeTZDtype
)
@final
@cache_readonly
def is_object(self) -> bool:
return self.values.dtype == _dtype_obj
@final
@cache_readonly
def is_extension(self) -> bool:
return not lib.is_np_dtype(self.values.dtype)
@final
@cache_readonly
def _can_consolidate(self) -> bool:
# We _could_ consolidate for DatetimeTZDtype but don't for now.
return not self.is_extension
@final
@cache_readonly
def _consolidate_key(self):
return self._can_consolidate, self.dtype.name
@final
@cache_readonly
def _can_hold_na(self) -> bool:
"""
Can we store NA values in this Block?
"""
dtype = self.dtype
if isinstance(dtype, np.dtype):
return dtype.kind not in "iub"
return dtype._can_hold_na
@final
@property
def is_bool(self) -> bool:
"""
We can be bool if a) we are bool dtype or b) object dtype with bool objects.
"""
return self.values.dtype == np.dtype(bool)
@final
def external_values(self):
return external_values(self.values)
@final
@cache_readonly
def fill_value(self):
# Used in reindex_indexer
return na_value_for_dtype(self.dtype, compat=False)
@final
def _standardize_fill_value(self, value):
# if we are passed a scalar None, convert it here
if self.dtype != _dtype_obj and is_valid_na_for_dtype(value, self.dtype):
value = self.fill_value
return value
@property
def mgr_locs(self) -> BlockPlacement:
return self._mgr_locs
@mgr_locs.setter
def mgr_locs(self, new_mgr_locs: BlockPlacement) -> None:
self._mgr_locs = new_mgr_locs
@final
def make_block(
self,
values,
placement: BlockPlacement | None = None,
refs: BlockValuesRefs | None = None,
) -> Block:
"""
Create a new block, with type inference propagate any values that are
not specified
"""
if placement is None:
placement = self._mgr_locs
if self.is_extension:
values = ensure_block_shape(values, ndim=self.ndim)
return new_block(values, placement=placement, ndim=self.ndim, refs=refs)
@final
def make_block_same_class(
self,
values,
placement: BlockPlacement | None = None,
refs: BlockValuesRefs | None = None,
) -> Self:
"""Wrap given values in a block of same type as self."""
# Pre-2.0 we called ensure_wrapped_if_datetimelike because fastparquet
# relied on it, as of 2.0 the caller is responsible for this.
if placement is None:
placement = self._mgr_locs
# We assume maybe_coerce_values has already been called
return type(self)(values, placement=placement, ndim=self.ndim, refs=refs)
@final
def __repr__(self) -> str:
# don't want to print out all of the items here
name = type(self).__name__
if self.ndim == 1:
result = f"{name}: {len(self)} dtype: {self.dtype}"
else:
shape = " x ".join([str(s) for s in self.shape])
result = f"{name}: {self.mgr_locs.indexer}, {shape}, dtype: {self.dtype}"
return result
@final
def __len__(self) -> int:
return len(self.values)
@final
def slice_block_columns(self, slc: slice) -> Self:
"""
Perform __getitem__-like, return result as block.
"""
new_mgr_locs = self._mgr_locs[slc]
new_values = self._slice(slc)
refs = self.refs
return type(self)(new_values, new_mgr_locs, self.ndim, refs=refs)
@final
def take_block_columns(self, indices: npt.NDArray[np.intp]) -> Self:
"""
Perform __getitem__-like, return result as block.
Only supports slices that preserve dimensionality.
"""
# Note: only called from is from internals.concat, and we can verify
# that never happens with 1-column blocks, i.e. never for ExtensionBlock.
new_mgr_locs = self._mgr_locs[indices]
new_values = self._slice(indices)
return type(self)(new_values, new_mgr_locs, self.ndim, refs=None)
@final
def getitem_block_columns(
self, slicer: slice, new_mgr_locs: BlockPlacement, ref_inplace_op: bool = False
) -> Self:
"""
Perform __getitem__-like, return result as block.
Only supports slices that preserve dimensionality.
"""
new_values = self._slice(slicer)
refs = self.refs if not ref_inplace_op or self.refs.has_reference() else None
return type(self)(new_values, new_mgr_locs, self.ndim, refs=refs)
@final
def _can_hold_element(self, element: Any) -> bool:
"""require the same dtype as ourselves"""
element = extract_array(element, extract_numpy=True)
return can_hold_element(self.values, element)
@final
def should_store(self, value: ArrayLike) -> bool:
"""
Should we set self.values[indexer] = value inplace or do we need to cast?
Parameters
----------
value : np.ndarray or ExtensionArray
Returns
-------
bool
"""
return value.dtype == self.dtype
# ---------------------------------------------------------------------
# Apply/Reduce and Helpers
@final
def apply(self, func, **kwargs) -> list[Block]:
"""
apply the function to my values; return a block if we are not
one
"""
result = func(self.values, **kwargs)
result = maybe_coerce_values(result)
return self._split_op_result(result)
@final
def reduce(self, func) -> list[Block]:
# We will apply the function and reshape the result into a single-row
# Block with the same mgr_locs; squeezing will be done at a higher level
assert self.ndim == 2
result = func(self.values)
if self.values.ndim == 1:
res_values = result
else:
res_values = result.reshape(-1, 1)
nb = self.make_block(res_values)
return [nb]
@final
def _split_op_result(self, result: ArrayLike) -> list[Block]:
# See also: split_and_operate
if result.ndim > 1 and isinstance(result.dtype, ExtensionDtype):
# TODO(EA2D): unnecessary with 2D EAs
# if we get a 2D ExtensionArray, we need to split it into 1D pieces
nbs = []
for i, loc in enumerate(self._mgr_locs):
if not is_1d_only_ea_dtype(result.dtype):
vals = result[i : i + 1]
else:
vals = result[i]
bp = BlockPlacement(loc)
block = self.make_block(values=vals, placement=bp)
nbs.append(block)
return nbs
nb = self.make_block(result)
return [nb]
@final
def _split(self) -> list[Block]:
"""
Split a block into a list of single-column blocks.
"""
assert self.ndim == 2
new_blocks = []
for i, ref_loc in enumerate(self._mgr_locs):
vals = self.values[slice(i, i + 1)]
bp = BlockPlacement(ref_loc)
nb = type(self)(vals, placement=bp, ndim=2, refs=self.refs)
new_blocks.append(nb)
return new_blocks
@final
def split_and_operate(self, func, *args, **kwargs) -> list[Block]:
"""
Split the block and apply func column-by-column.
Parameters
----------
func : Block method
*args
**kwargs
Returns
-------
List[Block]
"""
assert self.ndim == 2 and self.shape[0] != 1
res_blocks = []
for nb in self._split():
rbs = func(nb, *args, **kwargs)
res_blocks.extend(rbs)
return res_blocks
# ---------------------------------------------------------------------
# Up/Down-casting
@final
def coerce_to_target_dtype(self, other, warn_on_upcast: bool = False) -> Block:
"""
coerce the current block to a dtype compat for other
we will return a block, possibly object, and not raise
we can also safely try to coerce to the same dtype
and will receive the same block
"""
new_dtype = find_result_type(self.values.dtype, other)
# In a future version of pandas, the default will be that
# setting `nan` into an integer series won't raise.
if (
is_scalar(other)
and is_integer_dtype(self.values.dtype)
and isna(other)
and other is not NaT
):
warn_on_upcast = False
elif (
isinstance(other, np.ndarray)
and other.ndim == 1
and is_integer_dtype(self.values.dtype)
and is_float_dtype(other.dtype)
and lib.has_only_ints_or_nan(other)
):
warn_on_upcast = False
if warn_on_upcast:
warnings.warn(
f"Setting an item of incompatible dtype is deprecated "
"and will raise in a future error of pandas. "
f"Value '{other}' has dtype incompatible with {self.values.dtype}, "
"please explicitly cast to a compatible dtype first.",
FutureWarning,
stacklevel=find_stack_level(),
)
if self.values.dtype == new_dtype:
raise AssertionError(
f"Did not expect new dtype {new_dtype} to equal self.dtype "
f"{self.values.dtype}. Please report a bug at "
"https://github.com/pandas-dev/pandas/issues."
)
return self.astype(new_dtype, copy=False)
@final
def _maybe_downcast(
self, blocks: list[Block], downcast, using_cow: bool, caller: str
) -> list[Block]:
if downcast is False:
return blocks
if self.dtype == _dtype_obj:
# TODO: does it matter that self.dtype might not match blocks[i].dtype?
# GH#44241 We downcast regardless of the argument;
# respecting 'downcast=None' may be worthwhile at some point,
# but ATM it breaks too much existing code.
# split and convert the blocks
nbs = extend_blocks(
[blk.convert(using_cow=using_cow, copy=not using_cow) for blk in blocks]
)
elif downcast is None:
return blocks
elif caller == "where" and get_option("future.no_silent_downcasting") is True:
return blocks
else:
nbs = extend_blocks([b._downcast_2d(downcast, using_cow) for b in blocks])
# When _maybe_downcast is called with caller="where", it is either
# a) with downcast=False, which is a no-op (the desired future behavior)
# b) with downcast="infer", which is _not_ passed by the user.
# In the latter case the future behavior is to stop doing inference,
# so we issue a warning if and only if some inference occurred.
if caller == "where":
# GH#53656
if len(blocks) != len(nbs) or any(
left.dtype != right.dtype for left, right in zip(blocks, nbs)
):
# In this case _maybe_downcast was _not_ a no-op, so the behavior
# will change, so we issue a warning.
warnings.warn(
"Downcasting behavior in Series and DataFrame methods 'where', "
"'mask', and 'clip' is deprecated. In a future "
"version this will not infer object dtypes or cast all-round "
"floats to integers. Instead call "
"result.infer_objects(copy=False) for object inference, "
"or cast round floats explicitly. To opt-in to the future "
"behavior, set "
"`pd.set_option('future.no_silent_downcasting', True)`",
FutureWarning,
stacklevel=find_stack_level(),
)
return nbs
@final
@maybe_split
def _downcast_2d(self, dtype, using_cow: bool = False) -> list[Block]:
"""
downcast specialized to 2D case post-validation.
Refactored to allow use of maybe_split.
"""
new_values = maybe_downcast_to_dtype(self.values, dtype=dtype)
new_values = maybe_coerce_values(new_values)
refs = self.refs if new_values is self.values else None
return [self.make_block(new_values, refs=refs)]
@final
def convert(
self,
*,
copy: bool = True,
using_cow: bool = False,
) -> list[Block]:
"""
Attempt to coerce any object types to better types. Return a copy
of the block (if copy = True).
"""
if not self.is_object:
if not copy and using_cow:
return [self.copy(deep=False)]
return [self.copy()] if copy else [self]
if self.ndim != 1 and self.shape[0] != 1:
blocks = self.split_and_operate(
Block.convert, copy=copy, using_cow=using_cow
)
if all(blk.dtype.kind == "O" for blk in blocks):
# Avoid fragmenting the block if convert is a no-op
if using_cow:
return [self.copy(deep=False)]
return [self.copy()] if copy else [self]
return blocks
values = self.values
if values.ndim == 2:
# the check above ensures we only get here with values.shape[0] == 1,
# avoid doing .ravel as that might make a copy
values = values[0]
res_values = lib.maybe_convert_objects(
values, # type: ignore[arg-type]
convert_non_numeric=True,
)
refs = None
if copy and res_values is values:
res_values = values.copy()
elif res_values is values:
refs = self.refs
res_values = ensure_block_shape(res_values, self.ndim)
res_values = maybe_coerce_values(res_values)
return [self.make_block(res_values, refs=refs)]
# ---------------------------------------------------------------------
# Array-Like Methods
@final
@cache_readonly
def dtype(self) -> DtypeObj:
return self.values.dtype
@final
def astype(
self,
dtype: DtypeObj,
copy: bool = False,
errors: IgnoreRaise = "raise",
using_cow: bool = False,
) -> Block:
"""
Coerce to the new dtype.
Parameters
----------
dtype : np.dtype or ExtensionDtype
copy : bool, default False
copy if indicated
errors : str, {'raise', 'ignore'}, default 'raise'
- ``raise`` : allow exceptions to be raised
- ``ignore`` : suppress exceptions. On error return original object
using_cow: bool, default False
Signaling if copy on write copy logic is used.
Returns
-------
Block
"""
values = self.values
new_values = astype_array_safe(values, dtype, copy=copy, errors=errors)
new_values = maybe_coerce_values(new_values)
refs = None
if (using_cow or not copy) and astype_is_view(values.dtype, new_values.dtype):
refs = self.refs
newb = self.make_block(new_values, refs=refs)
if newb.shape != self.shape:
raise TypeError(
f"cannot set astype for copy = [{copy}] for dtype "
f"({self.dtype.name} [{self.shape}]) to different shape "
f"({newb.dtype.name} [{newb.shape}])"
)
return newb
@final
def to_native_types(self, na_rep: str = "nan", quoting=None, **kwargs) -> Block:
"""convert to our native types format"""
result = to_native_types(self.values, na_rep=na_rep, quoting=quoting, **kwargs)
return self.make_block(result)
@final
def copy(self, deep: bool = True) -> Self:
"""copy constructor"""
values = self.values
refs: BlockValuesRefs | None
if deep:
values = values.copy()
refs = None
else:
refs = self.refs
return type(self)(values, placement=self._mgr_locs, ndim=self.ndim, refs=refs)
# ---------------------------------------------------------------------
# Copy-on-Write Helpers
@final
def _maybe_copy(self, using_cow: bool, inplace: bool) -> Self:
if using_cow and inplace:
deep = self.refs.has_reference()
blk = self.copy(deep=deep)
else:
blk = self if inplace else self.copy()
return blk
@final
def _get_refs_and_copy(self, using_cow: bool, inplace: bool):
refs = None
copy = not inplace
if inplace:
if using_cow and self.refs.has_reference():
copy = True
else:
refs = self.refs
return copy, refs
# ---------------------------------------------------------------------
# Replace
@final
def replace(
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,
using_cow: bool = False,
) -> list[Block]:
"""
replace the to_replace value with value, possible to create new
blocks here this is just a call to putmask.
"""
# Note: the checks we do in NDFrame.replace ensure we never get
# here with listlike to_replace or value, as those cases
# go through replace_list
values = self.values
if isinstance(values, Categorical):
# TODO: avoid special-casing
# GH49404
blk = self._maybe_copy(using_cow, inplace)
values = cast(Categorical, blk.values)
values._replace(to_replace=to_replace, value=value, inplace=True)
return [blk]
if not self._can_hold_element(to_replace):
# We cannot hold `to_replace`, so we know immediately that
# replacing it is a no-op.
# Note: If to_replace were a list, NDFrame.replace would call
# replace_list instead of replace.
if using_cow:
return [self.copy(deep=False)]
else:
return [self] if inplace else [self.copy()]
if mask is None:
mask = missing.mask_missing(values, to_replace)
if not mask.any():
# Note: we get here with test_replace_extension_other incorrectly
# bc _can_hold_element is incorrect.
if using_cow:
return [self.copy(deep=False)]
else:
return [self] if inplace else [self.copy()]
elif self._can_hold_element(value):
# TODO(CoW): Maybe split here as well into columns where mask has True
# and rest?
blk = self._maybe_copy(using_cow, inplace)
putmask_inplace(blk.values, mask, value)
if not (self.is_object and value is None):
# if the user *explicitly* gave None, we keep None, otherwise
# may downcast to NaN
if get_option("future.no_silent_downcasting") is True:
blocks = [blk]
else:
blocks = blk.convert(copy=False, using_cow=using_cow)
if len(blocks) > 1 or blocks[0].dtype != blk.dtype:
warnings.warn(
# GH#54710
"Downcasting behavior in `replace` is deprecated and "
"will be removed in a future version. To retain the old "
"behavior, explicitly call "
"`result.infer_objects(copy=False)`. "
"To opt-in to the future "
"behavior, set "
"`pd.set_option('future.no_silent_downcasting', True)`",
FutureWarning,
stacklevel=find_stack_level(),
)
else:
blocks = [blk]
return blocks
elif self.ndim == 1 or self.shape[0] == 1:
if value is None or value is NA:
blk = self.astype(np.dtype(object))
else:
blk = self.coerce_to_target_dtype(value)
return blk.replace(
to_replace=to_replace,
value=value,
inplace=True,
mask=mask,
)
else:
# split so that we only upcast where necessary
blocks = []
for i, nb in enumerate(self._split()):
blocks.extend(
type(self).replace(
nb,
to_replace=to_replace,
value=value,
inplace=True,
mask=mask[i : i + 1],
using_cow=using_cow,
)
)
return blocks
@final
def _replace_regex(
self,
to_replace,
value,
inplace: bool = False,
mask=None,
using_cow: bool = False,
) -> list[Block]:
"""
Replace elements by the given value.
Parameters
----------
to_replace : object or pattern
Scalar to replace or regular expression to match.
value : object
Replacement object.
inplace : bool, default False
Perform inplace modification.
mask : array-like of bool, optional
True indicate corresponding element is ignored.
using_cow: bool, default False
Specifying if copy on write is enabled.
Returns
-------
List[Block]
"""
if not self._can_hold_element(to_replace):
# i.e. only if self.is_object is True, but could in principle include a
# String ExtensionBlock
if using_cow:
return [self.copy(deep=False)]
return [self] if inplace else [self.copy()]
rx = re.compile(to_replace)
block = self._maybe_copy(using_cow, inplace)
replace_regex(block.values, rx, value, mask)
nbs = block.convert(copy=False, using_cow=using_cow)
opt = get_option("future.no_silent_downcasting")
if (len(nbs) > 1 or nbs[0].dtype != block.dtype) and not opt:
warnings.warn(
# GH#54710
"Downcasting behavior in `replace` is deprecated and "
"will be removed in a future version. To retain the old "
"behavior, explicitly call `result.infer_objects(copy=False)`. "
"To opt-in to the future "
"behavior, set "
"`pd.set_option('future.no_silent_downcasting', True)`",
FutureWarning,
stacklevel=find_stack_level(),
)
return nbs
@final
def replace_list(
self,
src_list: Iterable[Any],
dest_list: Sequence[Any],
inplace: bool = False,
regex: bool = False,
using_cow: bool = False,
) -> list[Block]:
"""
See BlockManager.replace_list docstring.
"""
values = self.values
if isinstance(values, Categorical):
# TODO: avoid special-casing
# GH49404
blk = self._maybe_copy(using_cow, inplace)
values = cast(Categorical, blk.values)
values._replace(to_replace=src_list, value=dest_list, inplace=True)
return [blk]
# Exclude anything that we know we won't contain
pairs = [
(x, y) for x, y in zip(src_list, dest_list) if self._can_hold_element(x)
]
if not len(pairs):
if using_cow:
return [self.copy(deep=False)]
# shortcut, nothing to replace
return [self] if inplace else [self.copy()]
src_len = len(pairs) - 1
if is_string_dtype(values.dtype):
# Calculate the mask once, prior to the call of comp
# in order to avoid repeating the same computations
na_mask = ~isna(values)
masks: Iterable[npt.NDArray[np.bool_]] = (
extract_bool_array(
cast(
ArrayLike,
compare_or_regex_search(
values, s[0], regex=regex, mask=na_mask
),
)
)
for s in pairs
)
else:
# GH#38086 faster if we know we dont need to check for regex
masks = (missing.mask_missing(values, s[0]) for s in pairs)
# Materialize if inplace = True, since the masks can change
# as we replace
if inplace:
masks = list(masks)
if using_cow:
# Don't set up refs here, otherwise we will think that we have
# references when we check again later
rb = [self]
else:
rb = [self if inplace else self.copy()]
opt = get_option("future.no_silent_downcasting")
for i, ((src, dest), mask) in enumerate(zip(pairs, masks)):
convert = i == src_len # only convert once at the end
new_rb: list[Block] = []
# GH-39338: _replace_coerce can split a block into
# single-column blocks, so track the index so we know
# where to index into the mask
for blk_num, blk in enumerate(rb):
if len(rb) == 1:
m = mask
else:
mib = mask
assert not isinstance(mib, bool)
m = mib[blk_num : blk_num + 1]
# error: Argument "mask" to "_replace_coerce" of "Block" has
# incompatible type "Union[ExtensionArray, ndarray[Any, Any], bool]";
# expected "ndarray[Any, dtype[bool_]]"
result = blk._replace_coerce(
to_replace=src,
value=dest,
mask=m,
inplace=inplace,
regex=regex,
using_cow=using_cow,
)
if using_cow and i != src_len:
# This is ugly, but we have to get rid of intermediate refs
# that did not go out of scope yet, otherwise we will trigger
# many unnecessary copies
for b in result:
ref = weakref.ref(b)
b.refs.referenced_blocks.pop(
b.refs.referenced_blocks.index(ref)
)
if (
not opt
and convert
and blk.is_object
and not all(x is None for x in dest_list)
):
# GH#44498 avoid unwanted cast-back
nbs = []
for res_blk in result:
converted = res_blk.convert(
copy=True and not using_cow, using_cow=using_cow
)
if len(converted) > 1 or converted[0].dtype != res_blk.dtype:
warnings.warn(
# GH#54710
"Downcasting behavior in `replace` is deprecated "
"and will be removed in a future version. To "
"retain the old behavior, explicitly call "
"`result.infer_objects(copy=False)`. "
"To opt-in to the future "
"behavior, set "
"`pd.set_option('future.no_silent_downcasting', True)`",
FutureWarning,
stacklevel=find_stack_level(),
)
nbs.extend(converted)
result = nbs
new_rb.extend(result)