Skip to content

Commit 86a4b5f

Browse files
use np.fromiter and update annotation
1 parent bda2878 commit 86a4b5f

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

pandas/core/dtypes/cast.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@
8787

8888
if TYPE_CHECKING:
8989
from collections.abc import (
90-
Iterable,
90+
Collection,
9191
Sequence,
9292
)
9393

@@ -1581,7 +1581,7 @@ def _maybe_box_and_unbox_datetimelike(value: Scalar, dtype: DtypeObj):
15811581
return _maybe_unbox_datetimelike(value, dtype)
15821582

15831583

1584-
def construct_1d_object_array_from_listlike(values: Iterable) -> np.ndarray:
1584+
def construct_1d_object_array_from_listlike(values: Collection) -> np.ndarray:
15851585
"""
15861586
Transform any list-like object in a 1-dimensional numpy array of object
15871587
dtype.
@@ -1599,12 +1599,9 @@ def construct_1d_object_array_from_listlike(values: Iterable) -> np.ndarray:
15991599
-------
16001600
1-dimensional numpy array of dtype object
16011601
"""
1602-
# numpy will try to interpret nested lists as further dimensions, hence
1603-
# making a 1D array that contains list-likes is a bit tricky:
1604-
result = np.empty(len(values), dtype="object")
1605-
for i, obj in enumerate(values):
1606-
result[i] = obj
1607-
return result
1602+
# numpy will try to interpret nested lists as further dimensions in np.array(),
1603+
# hence explicitly making a 1D array using np.fromiter
1604+
return np.fromiter(values, dtype="object", count=len(values))
16081605

16091606

16101607
def maybe_cast_to_integer_array(arr: list | np.ndarray, dtype: np.dtype) -> np.ndarray:

0 commit comments

Comments
 (0)