Skip to content

Commit 32613e0

Browse files
committed
REF: implement and use construct_1d_array_from_listlike
1 parent 96439fb commit 32613e0

File tree

2 files changed

+25
-12
lines changed

2 files changed

+25
-12
lines changed

pandas/core/common.py

+5-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,17 @@ 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+
if hasattr(values, '__array__'):
394+
values = [tuple(x) for x in values]
395+
result = construct_1d_array_from_listlike(values)
403396

404397
return result
405398

pandas/core/dtypes/cast.py

+20
Original file line numberDiff line numberDiff line change
@@ -1162,3 +1162,23 @@ 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+
Returns
1177+
-------
1178+
1-dimensional numpy array of dtype "dtype"
1179+
"""
1180+
# numpy will try to interpret nested lists as further dimensions, hence
1181+
# making a 1D array that contains list-likes is a bit tricky:
1182+
result = np.empty(len(values), dtype=dtype)
1183+
result[:] = values
1184+
return result

0 commit comments

Comments
 (0)