Skip to content

REF: simplify casting of scalars to array #38313

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 4 commits into from
Dec 7, 2020
Merged
Show file tree
Hide file tree
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
31 changes: 1 addition & 30 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
ints_to_pytimedelta,
)
from pandas._libs.tslibs.timezones import tz_compare
from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Scalar, Shape
from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Scalar
from pandas.util._validators import validate_bool_kwarg

from pandas.core.dtypes.common import (
Expand Down Expand Up @@ -1563,35 +1563,6 @@ def find_common_type(types: List[DtypeObj]) -> DtypeObj:
return np.find_common_type(types, [])


def cast_scalar_to_array(
shape: Shape, value: Scalar, dtype: Optional[DtypeObj] = None
) -> np.ndarray:
"""
Create np.ndarray of specified shape and dtype, filled with values.

Parameters
----------
shape : tuple
value : scalar value
dtype : np.dtype, optional
dtype to coerce

Returns
-------
ndarray of shape, filled with value, of specified / inferred dtype

"""
if dtype is None:
dtype, fill_value = infer_dtype_from_scalar(value)
else:
fill_value = value

values = np.empty(shape, dtype=dtype)
values.fill(fill_value)

return values


def construct_1d_arraylike_from_scalar(
value: Scalar, length: int, dtype: DtypeObj
) -> ArrayLike:
Expand Down
23 changes: 6 additions & 17 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@
)

from pandas.core.dtypes.cast import (
cast_scalar_to_array,
construct_1d_arraylike_from_scalar,
find_common_type,
infer_dtype_from_scalar,
Expand Down Expand Up @@ -615,9 +614,8 @@ def __init__(
if arr.ndim != 0:
raise ValueError("DataFrame constructor not properly called!")

values = cast_scalar_to_array(
(len(index), len(columns)), data, dtype=dtype
)
shape = (len(index), len(columns))
values = np.full(shape, arr)

mgr = init_ndarray(
values, index, columns, dtype=values.dtype, copy=False
Expand Down Expand Up @@ -3914,20 +3912,11 @@ def reindexer(value):

else:
# cast ignores pandas dtypes. so save the dtype first
infer_dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)
infer_dtype, fill_value = infer_dtype_from_scalar(value, pandas_dtype=True)

# upcast
if is_extension_array_dtype(infer_dtype):
value = construct_1d_arraylike_from_scalar(
value, len(self.index), infer_dtype
)
else:
# pandas\core\frame.py:3827: error: Argument 1 to
# "cast_scalar_to_array" has incompatible type "int"; expected
# "Tuple[Any, ...]" [arg-type]
value = cast_scalar_to_array(
len(self.index), value # type: ignore[arg-type]
)
value = construct_1d_arraylike_from_scalar(
fill_value, len(self), infer_dtype
)

value = maybe_cast_to_datetime(value, infer_dtype)

Expand Down
27 changes: 1 addition & 26 deletions pandas/tests/dtypes/cast/test_infer_dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@
import numpy as np
import pytest

from pandas.core.dtypes.cast import (
cast_scalar_to_array,
infer_dtype_from_array,
infer_dtype_from_scalar,
)
from pandas.core.dtypes.cast import infer_dtype_from_array, infer_dtype_from_scalar
from pandas.core.dtypes.common import is_dtype_equal

from pandas import (
Expand All @@ -19,7 +15,6 @@
Timestamp,
date_range,
)
import pandas._testing as tm


@pytest.fixture(params=[True, False])
Expand Down Expand Up @@ -176,23 +171,3 @@ def test_infer_dtype_from_scalar_errors():
def test_infer_dtype_from_array(arr, expected, pandas_dtype):
dtype, _ = infer_dtype_from_array(arr, pandas_dtype=pandas_dtype)
assert is_dtype_equal(dtype, expected)


@pytest.mark.parametrize(
"obj,dtype",
[
(1, np.int64),
(1.1, np.float64),
(Timestamp("2011-01-01"), "datetime64[ns]"),
(Timestamp("2011-01-01", tz="US/Eastern"), object),
(Period("2011-01-01", freq="D"), object),
],
)
def test_cast_scalar_to_array(obj, dtype):
shape = (3, 2)

exp = np.empty(shape, dtype=dtype)
exp.fill(obj)

arr = cast_scalar_to_array(shape, obj, dtype=dtype)
tm.assert_numpy_array_equal(arr, exp)