Skip to content

Commit d4d02a2

Browse files
committed
REF: implement and use construct_1d_array_from_listlike
1 parent b5f1e71 commit d4d02a2

File tree

2 files changed

+31
-12
lines changed

2 files changed

+31
-12
lines changed

pandas/core/common.py

+6-12
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from pandas.core.dtypes.missing import isna, isnull, notnull # noqa
2222
from pandas.api import types
2323
from pandas.core.dtypes import common
24+
from pandas.core.dtypes.cast import construct_1d_array_from_listlike
2425

2526
# compat
2627
from pandas.errors import ( # noqa
@@ -381,25 +382,18 @@ def _asarray_tuplesafe(values, dtype=None):
381382
return values.values
382383

383384
if isinstance(values, list) and dtype in [np.object_, object]:
384-
return lib.list_to_object_array(values)
385+
return construct_1d_array_from_listlike(values)
385386

386387
result = np.asarray(values, dtype=dtype)
387388

388389
if issubclass(result.dtype.type, compat.string_types):
389390
result = np.asarray(values, dtype=object)
390391

391392
if result.ndim == 2:
392-
if isinstance(values, list):
393-
return lib.list_to_object_array(values)
394-
else:
395-
# Making a 1D array that safely contains tuples is a bit tricky
396-
# in numpy, leading to the following
397-
try:
398-
result = np.empty(len(values), dtype=object)
399-
result[:] = values
400-
except ValueError:
401-
# we have a list-of-list
402-
result[:] = [tuple(x) for x in values]
393+
# Avoid building an array of arrays:
394+
# TODO: verify whether any path hits this except #18819 (invalid)
395+
values = [tuple(x) for x in values]
396+
result = construct_1d_array_from_listlike(values)
403397

404398
return result
405399

pandas/core/dtypes/cast.py

+25
Original file line numberDiff line numberDiff line change
@@ -1162,3 +1162,28 @@ def construct_1d_arraylike_from_scalar(value, length, dtype):
11621162
subarr.fill(value)
11631163

11641164
return subarr
1165+
1166+
1167+
def construct_1d_array_from_listlike(values, dtype='object'):
1168+
"""
1169+
Transform any list-like object in a 1-dimensional numpy array.
1170+
1171+
Parameters
1172+
----------
1173+
values : any iterable which has a len()
1174+
dtype : dtype, default 'object'
1175+
1176+
Raises
1177+
------
1178+
TypeError
1179+
* If `values` does not have a len()
1180+
1181+
Returns
1182+
-------
1183+
1-dimensional numpy array of dtype "dtype"
1184+
"""
1185+
# numpy will try to interpret nested lists as further dimensions, hence
1186+
# making a 1D array that contains list-likes is a bit tricky:
1187+
result = np.empty(len(values), dtype=dtype)
1188+
result[:] = values
1189+
return result

0 commit comments

Comments
 (0)