From 239ae6d24be8a6f7b516a894f7ada62ddf55ee7c Mon Sep 17 00:00:00 2001 From: onesandzeroes Date: Wed, 4 Jun 2014 23:11:27 +1000 Subject: [PATCH] BUG: Series.map fails when mapping a dict with tuple keys Explicitly use keys as index to prevent conversion to MultiIndex Add test for mapping with tuple-keyed dict Specify expected output for the test and use assert_series_equal Add note to v0.14.1 release notes --- doc/source/v0.14.1.txt | 1 + pandas/core/series.py | 2 +- pandas/tests/test_series.py | 19 +++++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/doc/source/v0.14.1.txt b/doc/source/v0.14.1.txt index ff35ce9ca3069..60dbaf9d7427e 100644 --- a/doc/source/v0.14.1.txt +++ b/doc/source/v0.14.1.txt @@ -116,3 +116,4 @@ Bug Fixes - Bug in ``CustomBusinessDay.apply`` raiases ``NameError`` when ``np.datetime64`` object is passed (:issue:`7196`) - Bug in ``MultiIndex.append``, ``concat`` and ``pivot_table`` don't preserve timezone (:issue:`6606`) - Bug all ``StringMethods`` now work on empty Series (:issue:`7242`) +- Bug in ``Series.map`` when mapping a dict with tuple keys of different lengths (:issue:`7333`) diff --git a/pandas/core/series.py b/pandas/core/series.py index ea3656662ab06..b66b74a011c4d 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1940,7 +1940,7 @@ def map_f(values, f): if isinstance(arg, (dict, Series)): if isinstance(arg, dict): - arg = self._constructor(arg) + arg = self._constructor(arg, index=arg.keys()) indexer = arg.index.get_indexer(values) new_values = com.take_1d(arg.values, indexer) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 44587248e6d51..6421986d75f61 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -4860,6 +4860,25 @@ def test_map_na_exclusion(self): exp = s * 2 assert_series_equal(result, exp) + def test_map_dict_with_tuple_keys(self): + ''' + Due to new MultiIndex-ing behaviour in v0.14.0, + dicts with tuple keys passed to map were being + converted to a multi-index, preventing tuple values + from being mapped properly. + ''' + df = pd.DataFrame({'a': [(1,), (2,), (3, 4), (5, 6)]}) + label_mappings = { + (1,): 'A', + (2,): 'B', + (3, 4): 'A', + (5, 6): 'B' + } + df['labels'] = df['a'].map(label_mappings) + df['expected_labels'] = pd.Series(['A', 'B', 'A', 'B'], index=df.index) + # All labels should be filled now + tm.assert_series_equal(df['labels'], df['expected_labels']) + def test_apply(self): assert_series_equal(self.ts.apply(np.sqrt), np.sqrt(self.ts))