Skip to content

Commit 2eed174

Browse files
committed
REF: implement and use _as_1d_array
1 parent b9dbdbb commit 2eed174

File tree

2 files changed

+26
-15
lines changed

2 files changed

+26
-15
lines changed

pandas/core/common.py

+24-12
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,26 @@ def intersection(*seqs):
372372
return type(seqs[0])(list(result))
373373

374374

375+
def _as_1d_array(values, dtype='object'):
376+
"""
377+
Transform any list-like object in a 1-dimensional numpy array.
378+
379+
Parameters
380+
----------
381+
values : any iterable which has a len()
382+
dtype : dtype, default 'object'
383+
384+
Returns
385+
-------
386+
1-dimensional numpy array
387+
"""
388+
# Making a 1D array that safely contains list-likes is a bit tricky
389+
# in numpy, leading to the following
390+
result = np.empty(len(values), dtype=dtype)
391+
result[:] = values
392+
return result
393+
394+
375395
def _asarray_tuplesafe(values, dtype=None):
376396
from pandas.core.index import Index
377397

@@ -381,25 +401,17 @@ def _asarray_tuplesafe(values, dtype=None):
381401
return values.values
382402

383403
if isinstance(values, list) and dtype in [np.object_, object]:
384-
return lib.list_to_object_array(values)
404+
return _as_1d_array(values)
385405

386406
result = np.asarray(values, dtype=dtype)
387407

388408
if issubclass(result.dtype.type, compat.string_types):
389409
result = np.asarray(values, dtype=object)
390410

391411
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]
412+
if hasattr(values, '__array__'):
413+
values = [tuple(x) for x in values]
414+
result = _as_1d_array(values)
403415

404416
return result
405417

pandas/core/series.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
from pandas.core.common import (is_bool_indexer,
4242
_default_index,
4343
_asarray_tuplesafe,
44+
_as_1d_array,
4445
_values_from_object,
4546
_maybe_match_name,
4647
SettingWithCopyError,
@@ -3214,9 +3215,7 @@ def _try_cast(arr, take_fast_path):
32143215

32153216
elif isinstance(data, (list, tuple)) and len(data) > 0:
32163217
if all(is_list_like(item) for item in data):
3217-
# Ensure nested lists are not interpreted as further dimensions:
3218-
subarr = np.empty(len(data), dtype='object')
3219-
subarr[:] = data
3218+
subarr = _as_1d_array(data)
32203219
elif dtype is not None:
32213220
try:
32223221
subarr = _try_cast(data, False)

0 commit comments

Comments
 (0)