Skip to content

Commit ad24cf7

Browse files
committed
Makes changes based on feedback from @jreback
1 parent 1e8ed10 commit ad24cf7

File tree

9 files changed

+65
-104
lines changed

9 files changed

+65
-104
lines changed

pandas/core/indexes/base.py

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

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

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

26902692
def _maybe_promote(self, other):
@@ -2730,8 +2732,9 @@ def map(self, mapper):
27302732
27312733
Parameters
27322734
----------
2733-
mapper : Union[function, dict, Series]
2735+
mapper : {callable, dict, Series}
27342736
Function to be applied or input correspondence object.
2737+
dict and Series support new in 0.20.0.
27352738
27362739
Returns
27372740
-------
@@ -2748,7 +2751,7 @@ def map(self, mapper):
27482751
mapped_values = algos.take_1d(mapper.values, indexer)
27492752
elif isinstance(mapper, dict):
27502753
idx = Index(mapper.keys())
2751-
data = idx.get_values_from_dict(mapper)
2754+
data = idx._get_values_from_dict(mapper)
27522755
indexer = idx.get_indexer(self.values)
27532756
mapped_values = algos.take_1d(data, indexer)
27542757
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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
189189
index = Index(_try_sort(data))
190190

191191
try:
192-
data = index.get_values_from_dict(data)
192+
data = index._get_values_from_dict(data)
193193
except TypeError:
194194
data = ([data.get(i, nan) for i in index]
195195
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
@@ -822,60 +822,32 @@ def test_map_tseries_indices_return_index(self):
822822
tm.assert_index_equal(exp, date_index.map(lambda x: x.hour))
823823

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

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

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

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

867-
def test_map_with_categorical_series(self):
868-
# GH 12756
869-
a = Index([1, 2, 3, 4])
870-
b = Series(["even", "odd", "even", "odd"],
871-
dtype="category")
872-
c = Series(["even", "odd", "even", "odd"])
873-
874-
exp = CategoricalIndex(["odd", "even", "odd", np.nan])
875-
tm.assert_index_equal(a.map(b), exp)
876-
exp = Index(["odd", "even", "odd", np.nan])
877-
tm.assert_index_equal(a.map(c), exp)
878-
879851
def test_map_with_non_function_missing_values(self):
880852
# GH 12756
881853
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
@@ -442,3 +442,21 @@ def test_indexing_with_category(self):
442442

443443
res = (cat[['A']] == 'foo')
444444
tm.assert_frame_equal(res, exp)
445+
446+
def test_map_with_dict_or_series(self):
447+
orig_values = ['a', 'B', 1, 'a']
448+
new_values = ['one', 2, 3.0, 'one']
449+
cur_index = pd.CategoricalIndex(orig_values, name='XXX')
450+
expected = pd.CategoricalIndex(new_values,
451+
name='XXX', categories=[3.0, 2, 'one'])
452+
453+
mapper = pd.Series(new_values[:-1], index=orig_values[:-1])
454+
output = cur_index.map(mapper)
455+
# Order of categories in output can be different
456+
tm.assert_index_equal(expected, output)
457+
458+
mapper = {o: n for o, n in
459+
zip(orig_values[:-1], new_values[:-1])}
460+
output = cur_index.map(mapper)
461+
# Order of categories in output can be different
462+
tm.assert_index_equal(expected, output)

0 commit comments

Comments
 (0)