Skip to content

Commit dfaca11

Browse files
jbrockmendelproost
authored andcommitted
maybe_promote: Restrict fill_value to scalar for non-object dtype (pandas-dev#29416)
1 parent 4dfc79e commit dfaca11

File tree

4 files changed

+96
-499
lines changed

4 files changed

+96
-499
lines changed

pandas/core/dtypes/cast.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,11 @@ def changeit():
339339

340340

341341
def maybe_promote(dtype, fill_value=np.nan):
342+
if not is_scalar(fill_value) and not is_object_dtype(dtype):
343+
# with object dtype there is nothing to promote, and the user can
344+
# pass pretty much any weird fill_value they like
345+
raise ValueError("fill_value must be a scalar")
346+
342347
# if we passed an array here, determine the fill value by dtype
343348
if isinstance(fill_value, np.ndarray):
344349
if issubclass(fill_value.dtype.type, (np.datetime64, np.timedelta64)):
@@ -686,7 +691,8 @@ def maybe_upcast(values, fill_value=np.nan, dtype=None, copy=False):
686691
dtype : if None, then use the dtype of the values, else coerce to this type
687692
copy : if True always make a copy even if no upcast is required
688693
"""
689-
if not is_scalar(fill_value):
694+
if not is_scalar(fill_value) and not is_object_dtype(values.dtype):
695+
# We allow arbitrary fill values for object dtype
690696
raise ValueError("fill_value must be a scalar")
691697

692698
if is_extension_type(values):

pandas/core/internals/blocks.py

-4
Original file line numberDiff line numberDiff line change
@@ -1283,10 +1283,6 @@ def diff(self, n: int, axis: int = 1) -> List["Block"]:
12831283
def shift(self, periods, axis=0, fill_value=None):
12841284
""" shift the block by periods, possibly upcast """
12851285

1286-
if not lib.is_scalar(fill_value):
1287-
# We could go further and require e.g. self._can_hold_element(fv)
1288-
raise ValueError("fill_value must be a scalar")
1289-
12901286
# convert integer to float if necessary. need to do a lot more than
12911287
# that, handle boolean etc also
12921288
new_values, fill_value = maybe_upcast(self.values, fill_value)

0 commit comments

Comments
 (0)