Skip to content
Prev Previous commit
Next Next commit
When dtype is_dict_like is true, use get() instead of `values()…
…` in `pd.Series.astype`
  • Loading branch information
BranYang authored and jreback committed Jun 30, 2017
commit 0280e5cf29548cf277deb4bd65844c2c23059ac0
4 changes: 2 additions & 2 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3509,10 +3509,10 @@ def astype(self, dtype, copy=True, errors='raise', **kwargs):
"""
if is_dict_like(dtype):
if self.ndim == 1: # i.e. Series
if len(dtype) > 1 or list(dtype.keys())[0] != self.name:
if len(dtype) > 1 or self.name not in dtype.keys():
raise KeyError('Only the Series name can be used for '
'the key in Series dtype mappings.')
new_type = list(dtype.values())[0]
new_type = dtype.get(self.name)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

new_type = dtype[self.name] is ok here now

return self.astype(new_type, copy, errors, **kwargs)
elif self.ndim > 2:
raise NotImplementedError(
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/frame/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,13 @@ def test_astype_dict_like(self, dtype_class):
assert_frame_equal(df, equiv)
assert_frame_equal(df, original)

# if dtypes provided is empty, the resulting DataFrame
# should be the same as the original DataFrame
dt7 = dtype_class({})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add issue number as a comment
use result =
rather than equiv

equiv = df.astype(dt7)
assert_frame_equal(df, equiv)
assert_frame_equal(df, original)

def test_astype_duplicate_col(self):
a1 = Series([1, 2, 3, 4, 5], name='a')
b = Series([0.1, 0.2, 0.4, 0.6, 0.8], name='b')
Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/series/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ def test_astype_dict_like(self, dtype_class):
with pytest.raises(KeyError):
s.astype(dt4)

# if dtypes provided is empty, it should error
dt5 = dtype_class({})
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not very sure about the desired behavior here. Should we return the Series unchanged if an empty dict/Series is passed? Or should we just raise like it is now? @jreback

with pytest.raises(KeyError):
s.astype(dt5)

def test_astype_generic_timestamp_deprecated(self):
# see gh-15524
data = [1]
Expand Down