Skip to content

Commit 4c2d6b4

Browse files
Backport PR #60461 on branch 2.3.x (PERF: improve construct_1d_object_array_from_listlike) (#60483)
Backport PR #60461: PERF: improve construct_1d_object_array_from_listlike Co-authored-by: Joris Van den Bossche <[email protected]>
1 parent 2b37c98 commit 4c2d6b4

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed

pandas/core/dtypes/cast.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,8 @@
8787

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

9494
from pandas._typing import (
@@ -1586,7 +1586,7 @@ def _maybe_box_and_unbox_datetimelike(value: Scalar, dtype: DtypeObj):
15861586
return _maybe_unbox_datetimelike(value, dtype)
15871587

15881588

1589-
def construct_1d_object_array_from_listlike(values: Sized) -> np.ndarray:
1589+
def construct_1d_object_array_from_listlike(values: Collection) -> np.ndarray:
15901590
"""
15911591
Transform any list-like object in a 1-dimensional numpy array of object
15921592
dtype.
@@ -1604,11 +1604,9 @@ def construct_1d_object_array_from_listlike(values: Sized) -> np.ndarray:
16041604
-------
16051605
1-dimensional numpy array of dtype object
16061606
"""
1607-
# numpy will try to interpret nested lists as further dimensions, hence
1608-
# making a 1D array that contains list-likes is a bit tricky:
1609-
result = np.empty(len(values), dtype="object")
1610-
result[:] = values
1611-
return result
1607+
# numpy will try to interpret nested lists as further dimensions in np.array(),
1608+
# hence explicitly making a 1D array using np.fromiter
1609+
return np.fromiter(values, dtype="object", count=len(values))
16121610

16131611

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

0 commit comments

Comments
 (0)