From 4a5569fb1eac53e75be31bee81fb49077ce0f1c7 Mon Sep 17 00:00:00 2001 From: Ka Wo Chen Date: Tue, 29 Dec 2015 13:48:25 -0500 Subject: [PATCH] API: GH11885 DataFrame.round() now returns non-numeric columns unchanged --- doc/source/whatsnew/v0.18.0.txt | 1 + pandas/core/frame.py | 9 +++++++-- pandas/tests/test_frame.py | 15 +++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/doc/source/whatsnew/v0.18.0.txt b/doc/source/whatsnew/v0.18.0.txt index 89ffd0b015846..4dd8a1d19c383 100644 --- a/doc/source/whatsnew/v0.18.0.txt +++ b/doc/source/whatsnew/v0.18.0.txt @@ -165,6 +165,7 @@ Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - The parameter ``out`` has been removed from the ``Series.round()`` method. (:issue:`11763`) +- ``DataFrame.round()`` leaves non-numeric columns unchanged in its return, rather than raises. (:issue:`11885`) Bug in QuarterBegin with n=0 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 781d4b8bddf12..fea9318349d0b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4416,10 +4416,15 @@ def round(self, decimals=0, out=None): def _dict_round(df, decimals): for col, vals in df.iteritems(): try: - yield vals.round(decimals[col]) + yield _series_round(vals, decimals[col]) except KeyError: yield vals + def _series_round(s, decimals): + if com.is_integer_dtype(s) or com.is_float_dtype(s): + return s.round(decimals) + return s + if isinstance(decimals, (dict, Series)): if isinstance(decimals, Series): if not decimals.index.is_unique: @@ -4427,7 +4432,7 @@ def _dict_round(df, decimals): new_cols = [col for col in _dict_round(self, decimals)] elif com.is_integer(decimals): # Dispatch to Series.round - new_cols = [v.round(decimals) for _, v in self.iteritems()] + new_cols = [_series_round(v, decimals) for _, v in self.iteritems()] else: raise TypeError("decimals must be an integer, a dict-like or a Series") diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index aa18c7826e544..57e75e3393b1b 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -13523,6 +13523,21 @@ def test_round(self): # Make sure this doesn't break existing Series.round tm.assert_series_equal(df['col1'].round(1), expected_rounded['col1']) + + def test_round_mixed_type(self): + # GH11885 + df = DataFrame({'col1': [1.1, 2.2, 3.3, 4.4], 'col2': ['1', 'a', 'c', 'f'], + 'col3': date_range('20111111', periods=4)}) + round_0 = DataFrame({'col1': [1., 2., 3., 4.], 'col2': ['1', 'a', 'c' ,'f'], + 'col3': date_range('20111111', periods=4)}) + tm.assert_frame_equal(df.round(), round_0) + tm.assert_frame_equal(df.round(1), df) + tm.assert_frame_equal(df.round({'col1':1}), df) + tm.assert_frame_equal(df.round({'col1':0}), round_0) + tm.assert_frame_equal(df.round({'col1':0, 'col2':1}), round_0) + tm.assert_frame_equal(df.round({'col3':1}), df) + + def test_round_issue(self): # GH11611