Skip to content

Commit a45ce6c

Browse files
committed
BUG: fix construction of Series from dict with nested lists
1 parent 6e56195 commit a45ce6c

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

doc/source/whatsnew/v0.22.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ Other
246246

247247
- Improved error message when attempting to use a Python keyword as an identifier in a numexpr query (:issue:`18221`)
248248
- Fixed a bug where creating a Series from an array that contains both tz-naive and tz-aware values will result in a Series whose dtype is tz-aware instead of object (:issue:`16406`)
249+
- Fixed construction of a :class:`Series` from a ``dict`` containing nested lists as values (:issue:`18625`)
249250
- Fixed construction of a :class:`Series` from a ``dict`` containing ``NaN`` as key (:issue:`18480`)
250251
- Adding a ``Period`` object to a ``datetime`` or ``Timestamp`` object will now correctly raise a ``TypeError`` (:issue:`17983`)
251252
-

pandas/core/series.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -3208,7 +3208,11 @@ def _try_cast(arr, take_fast_path):
32083208
return subarr
32093209

32103210
elif isinstance(data, (list, tuple)) and len(data) > 0:
3211-
if dtype is not None:
3211+
if all(is_list_like(item) for item in data):
3212+
# Ensure nested lists are not interpreted as further dimensions:
3213+
subarr = np.empty(len(data), dtype='object')
3214+
subarr[:] = data
3215+
elif dtype is not None:
32123216
try:
32133217
subarr = _try_cast(data, False)
32143218
except Exception:

pandas/tests/series/test_constructors.py

+11
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,17 @@ def test_constructor_dict(self):
651651
expected.iloc[1] = 1
652652
assert_series_equal(result, expected)
653653

654+
@pytest.mark.parametrize('input_class', [list, tuple])
655+
@pytest.mark.parametrize('dtype', ['object', None])
656+
def test_constructor_dict_nested_lists(self, input_class, dtype):
657+
# GH 18625
658+
d = {'a': input_class([input_class([1, 2, 3]),
659+
input_class([4, 5, 6])]),
660+
'b': input_class([input_class([7, 8, 9])])}
661+
result = Series(d, index=['a', 'b'], dtype=dtype)
662+
expected = Series([d['a'], d['b']], index=['a', 'b'])
663+
assert_series_equal(result, expected)
664+
654665
@pytest.mark.parametrize("value", [2, np.nan, None, float('nan')])
655666
def test_constructor_dict_nan_key(self, value):
656667
# GH 18480

0 commit comments

Comments
 (0)