Skip to content

REF: simplify maybe_upcast #38428

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 12, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 8 additions & 22 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -924,45 +924,31 @@ def maybe_infer_dtype_type(element):


def maybe_upcast(
values: ArrayLike,
values: np.ndarray,
fill_value: Scalar = np.nan,
dtype: Dtype = None,
copy: bool = False,
) -> Tuple[ArrayLike, Scalar]:
) -> Tuple[np.ndarray, Scalar]:
"""
Provide explicit type promotion and coercion.

Parameters
----------
values : ndarray or ExtensionArray
The array that we want to maybe upcast.
values : np.ndarray
The array that we may want to upcast.
fill_value : what we want to fill with
dtype : if None, then use the dtype of the values, else coerce to this type
copy : bool, default True
If True always make a copy even if no upcast is required.

Returns
-------
values: ndarray or ExtensionArray
values: np.ndarray
the original array, possibly upcast
fill_value:
the fill value, possibly upcast
"""
if not is_scalar(fill_value) and not is_object_dtype(values.dtype):
# We allow arbitrary fill values for object dtype
raise ValueError("fill_value must be a scalar")

if is_extension_array_dtype(values):
if copy:
values = values.copy()
else:
if dtype is None:
dtype = values.dtype
new_dtype, fill_value = maybe_promote(dtype, fill_value)
if new_dtype != values.dtype:
values = values.astype(new_dtype)
elif copy:
values = values.copy()
new_dtype, fill_value = maybe_promote(values.dtype, fill_value)
# We get a copy in all cases _except_ (values.dtype == new_dtype and not copy)
values = values.astype(new_dtype, copy=copy)

return values, fill_value

Expand Down