Skip to content

Commit 239ae6d

Browse files
committed
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
1 parent 4fed1e0 commit 239ae6d

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/source/v0.14.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,4 @@ Bug Fixes
116116
- Bug in ``CustomBusinessDay.apply`` raiases ``NameError`` when ``np.datetime64`` object is passed (:issue:`7196`)
117117
- Bug in ``MultiIndex.append``, ``concat`` and ``pivot_table`` don't preserve timezone (:issue:`6606`)
118118
- Bug all ``StringMethods`` now work on empty Series (:issue:`7242`)
119+
- Bug in ``Series.map`` when mapping a dict with tuple keys of different lengths (:issue:`7333`)

pandas/core/series.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1940,7 +1940,7 @@ def map_f(values, f):
19401940

19411941
if isinstance(arg, (dict, Series)):
19421942
if isinstance(arg, dict):
1943-
arg = self._constructor(arg)
1943+
arg = self._constructor(arg, index=arg.keys())
19441944

19451945
indexer = arg.index.get_indexer(values)
19461946
new_values = com.take_1d(arg.values, indexer)

pandas/tests/test_series.py

+19
Original file line numberDiff line numberDiff line change
@@ -4860,6 +4860,25 @@ def test_map_na_exclusion(self):
48604860
exp = s * 2
48614861
assert_series_equal(result, exp)
48624862

4863+
def test_map_dict_with_tuple_keys(self):
4864+
'''
4865+
Due to new MultiIndex-ing behaviour in v0.14.0,
4866+
dicts with tuple keys passed to map were being
4867+
converted to a multi-index, preventing tuple values
4868+
from being mapped properly.
4869+
'''
4870+
df = pd.DataFrame({'a': [(1,), (2,), (3, 4), (5, 6)]})
4871+
label_mappings = {
4872+
(1,): 'A',
4873+
(2,): 'B',
4874+
(3, 4): 'A',
4875+
(5, 6): 'B'
4876+
}
4877+
df['labels'] = df['a'].map(label_mappings)
4878+
df['expected_labels'] = pd.Series(['A', 'B', 'A', 'B'], index=df.index)
4879+
# All labels should be filled now
4880+
tm.assert_series_equal(df['labels'], df['expected_labels'])
4881+
48634882
def test_apply(self):
48644883
assert_series_equal(self.ts.apply(np.sqrt), np.sqrt(self.ts))
48654884

0 commit comments

Comments
 (0)