Skip to content

Commit e8f602b

Browse files
committed
BUG: fix initialization of Series with dict containing NaN as key
closes pandas-dev#18480 closes pandas-dev#18515
1 parent 7627cca commit e8f602b

File tree

6 files changed

+61
-19
lines changed

6 files changed

+61
-19
lines changed

doc/source/whatsnew/v0.22.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -208,5 +208,6 @@ Other
208208

209209
- Improved error message when attempting to use a Python keyword as an identifier in a numexpr query (:issue:`18221`)
210210
- Fixed a bug where creating a Series from an array that contains both tz-naive and tz-aware values will result in a Series whose dtype is tz-aware instead of object (:issue:`16406`)
211+
- Fixed construction of :class:`Series` from ``dict`` containing ``NaN`` as key (:issue:`18480`)
211212
- Adding a ``Period`` object to a ``datetime`` or ``Timestamp`` object will now correctly raise a ``TypeError`` (:issue:`17983`)
212213
-

pandas/core/base.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -874,9 +874,8 @@ def _map_values(self, mapper, na_action=None):
874874
# convert to an Series for efficiency.
875875
# we specify the keys here to handle the
876876
# possibility that they are tuples
877-
from pandas import Series, Index
878-
index = Index(mapper, tupleize_cols=False)
879-
mapper = Series(mapper, index=index)
877+
from pandas import Series
878+
mapper = Series(mapper)
880879

881880
if isinstance(mapper, ABCSeries):
882881
# Since values were input this means we came from either

pandas/core/series.py

+40-13
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
_default_index,
4343
_asarray_tuplesafe,
4444
_values_from_object,
45-
_try_sort,
4645
_maybe_match_name,
4746
SettingWithCopyError,
4847
_maybe_box_datetimelike,
@@ -198,18 +197,9 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
198197
data = data.reindex(index, copy=copy)
199198
data = data._data
200199
elif isinstance(data, dict):
201-
if index is None:
202-
if isinstance(data, OrderedDict):
203-
index = Index(data)
204-
else:
205-
index = Index(_try_sort(data))
206-
207-
try:
208-
data = index._get_values_from_dict(data)
209-
except TypeError:
210-
data = ([data.get(i, np.nan) for i in index]
211-
if data else np.nan)
212-
200+
data, index = self._init_dict(data, index, dtype)
201+
dtype = None
202+
copy = False
213203
elif isinstance(data, SingleBlockManager):
214204
if index is None:
215205
index = data.index
@@ -257,6 +247,43 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
257247
self.name = name
258248
self._set_axis(0, index, fastpath=True)
259249

250+
def _init_dict(self, data, index=None, dtype=None):
251+
"""
252+
Derive the "_data" and "index" attributes of a new Series from a
253+
dictionary input.
254+
255+
Parameters
256+
----------
257+
data : dict or dict-like
258+
Data used to populate the new Series
259+
index : Index or index-like, default None
260+
index for the new Series: if None, use dict keys
261+
dtype : dtype, default None
262+
dtype for the new Series: if None, infer from data
263+
264+
Returns
265+
-------
266+
_data : BlockManager for the new Series
267+
index : index for the new Series
268+
"""
269+
# Looking for NaN in dict doesn't work ({np.nan : 1}[float('nan')]
270+
# raises KeyError), so we iterate the entire dict, and align
271+
if data:
272+
keys, values = zip(*compat.iteritems(data))
273+
else:
274+
keys, values = [], []
275+
# Input is now list-like, so rely on "standard" construction:
276+
s = Series(values, index=keys, dtype=dtype)
277+
# Now we just make sure the order is respected, if any
278+
if index is not None and not index.identical(keys):
279+
s = s.reindex(index)
280+
elif not isinstance(data, OrderedDict):
281+
try:
282+
s = s.sort_index()
283+
except TypeError:
284+
pass
285+
return s._data, s.index
286+
260287
@classmethod
261288
def from_array(cls, arr, index=None, name=None, dtype=None, copy=False,
262289
fastpath=False):

pandas/tests/series/test_apply.py

+1
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,7 @@ def test_map_dict_with_tuple_keys(self):
422422
converted to a multi-index, preventing tuple values
423423
from being mapped properly.
424424
"""
425+
# GH 18496
425426
df = pd.DataFrame({'a': [(1, ), (2, ), (3, 4), (5, 6)]})
426427
label_mappings = {(1, ): 'A', (2, ): 'B', (3, 4): 'A', (5, 6): 'B'}
427428

pandas/tests/series/test_combine_concat.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,8 @@ def test_concat_empty_series_dtypes(self):
181181
# categorical
182182
assert pd.concat([Series(dtype='category'),
183183
Series(dtype='category')]).dtype == 'category'
184-
assert pd.concat([Series(dtype='category'),
184+
# GH 18515
185+
assert pd.concat([Series(np.array([]), dtype='category'),
185186
Series(dtype='float64')]).dtype == 'float64'
186187
assert pd.concat([Series(dtype='category'),
187188
Series(dtype='object')]).dtype == 'object'

pandas/tests/series/test_constructors.py

+15-2
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,21 @@ def test_constructor_dict(self):
625625
expected.iloc[1] = 1
626626
assert_series_equal(result, expected)
627627

628+
@pytest.mark.parametrize("value", [2, np.nan, None, float('nan')])
629+
def test_constructor_dict_nan_key(self, value):
630+
# GH 18480
631+
d = {1: 'a', value: 'b', float('nan'): 'c', 4: 'd'}
632+
result = Series(d).sort_values()
633+
expected = Series(['a', 'b', 'c', 'd'], index=[1, value, np.nan, 4])
634+
assert_series_equal(result, expected)
635+
636+
# MultiIndex:
637+
d = {(1, 1): 'a', (2, np.nan): 'b', (3, value): 'c'}
638+
result = Series(d).sort_values()
639+
expected = Series(['a', 'b', 'c'],
640+
index=Index([(1, 1), (2, np.nan), (3, value)]))
641+
assert_series_equal(result, expected)
642+
628643
def test_constructor_dict_datetime64_index(self):
629644
# GH 9456
630645

@@ -658,8 +673,6 @@ def test_constructor_tuple_of_tuples(self):
658673
s = Series(data)
659674
assert tuple(s) == data
660675

661-
@pytest.mark.xfail(reason='GH 18480 (Series initialization from dict with '
662-
'NaN keys')
663676
def test_constructor_dict_of_tuples(self):
664677
data = {(1, 2): 3,
665678
(None, 5): 6}

0 commit comments

Comments
 (0)