diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 0579a80aad28e..5bb8dc28dcd87 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -294,6 +294,8 @@ Indexing - Bug in tz-aware :class:`DatetimeIndex` where addition/subtraction with a :class:`TimedeltaIndex` or array with ``dtype='timedelta64[ns]'`` was incorrect (:issue:`17558`) - :func:`Index.to_series` now accepts ``index`` and ``name`` kwargs (:issue:`18699`) - :func:`DatetimeIndex.to_series` now accepts ``index`` and ``name`` kwargs (:issue:`18699`) +- Bug in indexing non-scalar value from ``Series`` having non-unique ``Index`` will return value flatted (:issue:`17610`) + I/O ^^^ diff --git a/pandas/core/series.py b/pandas/core/series.py index a3e7be1bfb35a..8fcb47948d724 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -664,13 +664,15 @@ def __getitem__(self, key): if not is_scalar(result): if is_list_like(result) and not isinstance(result, Series): - # we need to box if we have a non-unique index here + # we need to box if loc of the key isn't scalar here # otherwise have inline ndarray/lists - if not self.index.is_unique: - result = self._constructor( - result, index=[key] * len(result), - dtype=self.dtype).__finalize__(self) - + try: + if not is_scalar(self.index.get_loc(key)): + result = self._constructor( + result, index=[key] * len(result), + dtype=self.dtype).__finalize__(self) + except KeyError: + pass return result except InvalidIndexError: pass diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index b7381c6b8fd30..00fa980d9a139 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -547,6 +547,26 @@ def test_getitem_setitem_periodindex(self): result[4:8] = ts[4:8] assert_series_equal(result, ts) + @pytest.mark.parametrize( + 'result_1, duplicate_item, expected_1', + [ + [ + pd.Series({1: 12, 2: [1, 2, 2, 3]}), pd.Series({1: 313}), + pd.Series({1: 12, }, dtype=object), + ], + [ + pd.Series({1: [1, 2, 3], 2: [1, 2, 2, 3]}), + pd.Series({1: [1, 2, 3]}), pd.Series({1: [1, 2, 3], }), + ], + ]) + def test_getitem_with_duplicates_indices( + self, result_1, duplicate_item, expected_1): + # GH 17610 + result = result_1.append(duplicate_item) + expected = expected_1.append(duplicate_item) + assert_series_equal(result[1], expected) + assert result[2] == result_1[2] + def test_getitem_median_slice_bug(self): index = date_range('20090415', '20090519', freq='2B') s = Series(np.random.randn(13), index=index)