Skip to content

Commit 9e398a6

Browse files
authored
REF: de-special-case Block._maybe_downcast (#44205)
1 parent d48abea commit 9e398a6

File tree

1 file changed

+10
-40
lines changed

1 file changed

+10
-40
lines changed

pandas/core/internals/blocks.py

Lines changed: 10 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -510,54 +510,24 @@ def _maybe_downcast(self, blocks: list[Block], downcast=None) -> list[Block]:
510510
[blk.convert(datetime=True, numeric=False) for blk in blocks]
511511
)
512512

513-
# no need to downcast our float
514-
# unless indicated
515-
if downcast is None and self.dtype.kind in ["f", "c", "m", "M"]:
516-
# passing "infer" to maybe_downcast_to_dtype (via self.downcast)
517-
# would be a no-op, so we can short-circuit
513+
if downcast is None:
514+
return blocks
515+
if downcast is False:
516+
# turn if off completely
517+
# TODO: not reached, deprecate in favor of downcast=None
518518
return blocks
519519

520-
return extend_blocks([b.downcast(downcast) for b in blocks])
520+
return extend_blocks([b._downcast_2d(downcast) for b in blocks])
521521

522522
@final
523-
def downcast(self, dtypes=None) -> list[Block]:
524-
"""try to downcast each item to the dict of dtypes if present"""
525-
# turn it off completely
526-
if dtypes is False:
527-
return [self]
528-
529-
values = self.values
530-
531-
if self.ndim == 1:
532-
533-
# try to cast all non-floats here
534-
if dtypes is None:
535-
dtypes = "infer"
536-
537-
nv = maybe_downcast_to_dtype(values, dtypes)
538-
return [self.make_block(nv)]
539-
540-
# ndim > 1
541-
if dtypes is None:
542-
return [self]
543-
544-
if not (dtypes == "infer" or isinstance(dtypes, dict)):
545-
raise ValueError(
546-
"downcast must have a dictionary or 'infer' as its argument"
547-
)
548-
elif dtypes != "infer":
549-
raise AssertionError("dtypes as dict is not supported yet")
550-
551-
return self._downcast_2d()
552-
553523
@maybe_split
554-
def _downcast_2d(self) -> list[Block]:
524+
def _downcast_2d(self, dtype) -> list[Block]:
555525
"""
556526
downcast specialized to 2D case post-validation.
557527
558528
Refactored to allow use of maybe_split.
559529
"""
560-
new_values = maybe_downcast_to_dtype(self.values, dtype="infer")
530+
new_values = maybe_downcast_to_dtype(self.values, dtype=dtype)
561531
return [self.make_block(new_values)]
562532

563533
@final
@@ -1098,8 +1068,8 @@ def interpolate(
10981068
**kwargs,
10991069
)
11001070

1101-
nbs = [self.make_block_same_class(interp_values)]
1102-
return self._maybe_downcast(nbs, downcast)
1071+
nb = self.make_block_same_class(interp_values)
1072+
return nb._maybe_downcast([nb], downcast)
11031073

11041074
def take_nd(
11051075
self,

0 commit comments

Comments
 (0)