Skip to content

Commit 4311efb

Browse files
committed
Makes changes based on feedback from @jreback
1 parent 0fd9687 commit 4311efb

File tree

9 files changed

+66
-106
lines changed

9 files changed

+66
-106
lines changed

pandas/core/indexes/base.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2667,23 +2667,25 @@ def get_indexer_for(self, target, **kwargs):
26672667
indexer, _ = self.get_indexer_non_unique(target, **kwargs)
26682668
return indexer
26692669

2670-
def get_values_from_dict(self, input_dict):
2671-
"""Return the values of the input dictionary in the order the keys are
2670+
_index_shared_docs['_get_values_from_dict'] = """
2671+
Return the values of the input dictionary in the order the keys are
26722672
in the index. np.nan is returned for index values not in the
26732673
dictionary.
26742674
26752675
Parameters
26762676
----------
2677-
input_dict : dict
2677+
data : dict
26782678
The dictionary from which to extract the values
26792679
26802680
Returns
26812681
-------
2682-
Union[np.array, list]
2682+
np.array
26832683
26842684
"""
26852685

2686-
return lib.fast_multiget(input_dict, self.values,
2686+
@Appender(_index_shared_docs['_get_values_from_dict'])
2687+
def _get_values_from_dict(self, data):
2688+
return lib.fast_multiget(data, self.values,
26872689
default=np.nan)
26882690

26892691
def _maybe_promote(self, other):
@@ -2729,8 +2731,9 @@ def map(self, mapper):
27292731
27302732
Parameters
27312733
----------
2732-
mapper : Union[function, dict, Series]
2734+
mapper : {callable, dict, Series}
27332735
Function to be applied or input correspondence object.
2736+
dict and Series support new in 0.20.0.
27342737
27352738
Returns
27362739
-------
@@ -2747,7 +2750,7 @@ def map(self, mapper):
27472750
mapped_values = algos.take_1d(mapper.values, indexer)
27482751
elif isinstance(mapper, dict):
27492752
idx = Index(mapper.keys())
2750-
data = idx.get_values_from_dict(mapper)
2753+
data = idx._get_values_from_dict(mapper)
27512754
indexer = idx.get_indexer(self.values)
27522755
mapped_values = algos.take_1d(data, indexer)
27532756
else:

pandas/core/indexes/datetimelike.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,14 @@ def __rsub__(self, other):
704704
def _add_delta(self, other):
705705
return NotImplemented
706706

707+
@Appender(_index_shared_docs['_get_values_from_dict'])
708+
def _get_values_from_dict(self, data):
709+
if len(data):
710+
return np.array([data.get(i, np.nan)
711+
for i in self.asobject.values])
712+
713+
return np.array([np.nan])
714+
707715
def _add_delta_td(self, other):
708716
# add a delta of a timedeltalike
709717
# return the i8 result view

pandas/core/indexes/datetimes.py

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1398,29 +1398,16 @@ def get_value_maybe_box(self, series, key):
13981398
key, tz=self.tz)
13991399
return _maybe_box(self, values, series, key)
14001400

1401-
def get_values_from_dict(self, input_dict):
1402-
"""Return the values of the input dictionary in the order the keys are
1403-
in the index. np.nan is returned for index values not in the
1404-
dictionary.
1405-
1406-
Parameters
1407-
----------
1408-
input_dict : dict
1409-
The dictionary from which to extract the values
1410-
1411-
Returns
1412-
-------
1413-
Union[np.array, list]
1414-
1415-
"""
1416-
if len(input_dict):
1401+
@Appender(_index_shared_docs['_get_values_from_dict'])
1402+
def _get_values_from_dict(self, data):
1403+
if len(data):
14171404
# coerce back to datetime objects for lookup
1418-
input_dict = com._dict_compat(input_dict)
1419-
return lib.fast_multiget(input_dict,
1405+
data = com._dict_compat(data)
1406+
return lib.fast_multiget(data,
14201407
self.asobject.values,
14211408
default=np.nan)
1422-
else:
1423-
return np.nan
1409+
1410+
return np.array([np.nan])
14241411

14251412
def get_loc(self, key, method=None, tolerance=None):
14261413
"""

pandas/core/indexes/period.py

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -794,25 +794,6 @@ def _get_unique_index(self, dropna=False):
794794
res = res.dropna()
795795
return res
796796

797-
def get_values_from_dict(self, input_dict):
798-
"""Return the values of the input dictionary in the order the keys are
799-
in the index. np.nan is returned for index values not in the
800-
dictionary.
801-
802-
Parameters
803-
----------
804-
input_dict : dict
805-
The dictionary from which to extract the values
806-
807-
Returns
808-
-------
809-
Union[np.array, list]
810-
811-
"""
812-
813-
return np.array([input_dict.get(i, np.nan) for i in self.values]
814-
if input_dict else [np.nan])
815-
816797
def get_loc(self, key, method=None, tolerance=None):
817798
"""
818799
Get integer location for requested label

pandas/core/indexes/timedeltas.py

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -672,26 +672,6 @@ def get_value_maybe_box(self, series, key):
672672
values = self._engine.get_value(_values_from_object(series), key)
673673
return _maybe_box(self, values, series, key)
674674

675-
def get_values_from_dict(self, input_dict):
676-
"""Return the values of the input dictionary in the order the keys are
677-
in the index. np.nan is returned for index values not in the
678-
dictionary.
679-
680-
Parameters
681-
----------
682-
input_dict : dict
683-
The dictionary from which to extract the values
684-
685-
Returns
686-
-------
687-
Union[np.array, list]
688-
689-
"""
690-
691-
return np.array([input_dict.get(i, np.nan)
692-
for i in self.asobject.values]
693-
if input_dict else [np.nan])
694-
695675
def get_loc(self, key, method=None, tolerance=None):
696676
"""
697677
Get integer location for requested label

pandas/core/series.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@
4343
_try_sort,
4444
_maybe_match_name,
4545
SettingWithCopyError,
46-
_maybe_box_datetimelike,
47-
_dict_compat)
46+
_maybe_box_datetimelike)
4847
from pandas.core.index import (Index, MultiIndex, InvalidIndexError,
4948
Float64Index, _ensure_index)
5049
from pandas.core.indexing import check_bool_indexer, maybe_convert_indices
@@ -186,7 +185,7 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
186185
index = Index(_try_sort(data))
187186

188187
try:
189-
data = index.get_values_from_dict(data)
188+
data = index._get_values_from_dict(data)
190189
except TypeError:
191190
data = ([data.get(i, nan) for i in index]
192191
if data else np.nan)

pandas/tests/indexes/test_base.py

Lines changed: 9 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -823,60 +823,32 @@ def test_map_tseries_indices_return_index(self):
823823
tm.assert_index_equal(exp, date_index.map(lambda x: x.hour))
824824

825825
def test_map_with_dict_and_series(self):
826+
# GH 12756
826827
expected = Index(['foo', 'bar', 'baz'])
827828
mapper = Series(expected.values, index=[0, 1, 2])
828-
tm.assert_index_equal(tm.makeIntIndex(3).map(mapper), expected)
829-
830-
# GH 12766
831-
# special = []
832-
special = ['catIndex']
833-
834-
for name in special:
835-
orig_values = ['a', 'B', 1, 'a']
836-
new_values = ['one', 2, 3.0, 'one']
837-
cur_index = CategoricalIndex(orig_values, name='XXX')
838-
expected = CategoricalIndex(new_values,
839-
name='XXX', categories=[3.0, 2, 'one'])
840-
841-
mapper = pd.Series(new_values[:-1], index=orig_values[:-1])
842-
output = cur_index.map(mapper)
843-
# Order of categories in output can be different
844-
tm.assert_index_equal(expected, output)
829+
result = tm.makeIntIndex(3).map(mapper)
830+
tm.assert_index_equal(result, expected)
845831

846-
mapper = {o: n for o, n in
847-
zip(orig_values[:-1], new_values[:-1])}
848-
output = cur_index.map(mapper)
849-
# Order of categories in output can be different
850-
tm.assert_index_equal(expected, output)
832+
for name in self.indices.keys():
833+
if name == 'catIndex':
834+
# Tested in test_categorical
835+
continue
851836

852-
for name in list(set(self.indices.keys()) - set(special)):
853837
cur_index = self.indices[name]
854838
expected = Index(np.arange(len(cur_index), 0, -1))
855839
mapper = pd.Series(expected, index=cur_index)
856840
tm.assert_index_equal(expected, cur_index.map(mapper))
857841

858842
mapper = {o: n for o, n in
859843
zip(cur_index, expected)}
844+
# If the mapper is empty the expected index type is Int64Index
845+
# but the output defaults to Float64 so I treat it independently
860846
if mapper:
861847
tm.assert_index_equal(expected, cur_index.map(mapper))
862848
else:
863-
# The expected index type is Int64Index
864-
# but the output defaults to Float64
865849
tm.assert_index_equal(Float64Index([]),
866850
cur_index.map(mapper))
867851

868-
def test_map_with_categorical_series(self):
869-
# GH 12756
870-
a = Index([1, 2, 3, 4])
871-
b = Series(["even", "odd", "even", "odd"],
872-
dtype="category")
873-
c = Series(["even", "odd", "even", "odd"])
874-
875-
exp = CategoricalIndex(["odd", "even", "odd", np.nan])
876-
tm.assert_index_equal(a.map(b), exp)
877-
exp = Index(["odd", "even", "odd", np.nan])
878-
tm.assert_index_equal(a.map(c), exp)
879-
880852
def test_map_with_non_function_missing_values(self):
881853
# GH 12756
882854
expected = Index([2., np.nan, 'foo'])

pandas/tests/indexes/test_category.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,18 @@ def f(x):
240240
result = ci.map({'A': 10, 'B': 20, 'C': 30})
241241
tm.assert_index_equal(result, exp)
242242

243+
def test_map_with_categorical_series(self):
244+
# GH 12756
245+
a = pd.Index([1, 2, 3, 4])
246+
b = pd.Series(["even", "odd", "even", "odd"],
247+
dtype="category")
248+
c = pd.Series(["even", "odd", "even", "odd"])
249+
250+
exp = CategoricalIndex(["odd", "even", "odd", np.nan])
251+
tm.assert_index_equal(a.map(b), exp)
252+
exp = pd.Index(["odd", "even", "odd", np.nan])
253+
tm.assert_index_equal(a.map(c), exp)
254+
243255
def test_where(self):
244256
i = self.create_index()
245257
result = i.where(notnull(i))

pandas/tests/indexing/test_categorical.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,3 +407,21 @@ def test_indexing_with_category(self):
407407

408408
res = (cat[['A']] == 'foo')
409409
tm.assert_frame_equal(res, exp)
410+
411+
def test_map_with_dict_or_series(self):
412+
orig_values = ['a', 'B', 1, 'a']
413+
new_values = ['one', 2, 3.0, 'one']
414+
cur_index = pd.CategoricalIndex(orig_values, name='XXX')
415+
expected = pd.CategoricalIndex(new_values,
416+
name='XXX', categories=[3.0, 2, 'one'])
417+
418+
mapper = pd.Series(new_values[:-1], index=orig_values[:-1])
419+
output = cur_index.map(mapper)
420+
# Order of categories in output can be different
421+
tm.assert_index_equal(expected, output)
422+
423+
mapper = {o: n for o, n in
424+
zip(orig_values[:-1], new_values[:-1])}
425+
output = cur_index.map(mapper)
426+
# Order of categories in output can be different
427+
tm.assert_index_equal(expected, output)

0 commit comments

Comments
 (0)