Skip to content

Fix To Numeric on Decimal Fields #14839

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.20.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,5 @@ Performance Improvements

Bug Fixes
~~~~~~~~~

- Bug in ``DataFrame(..).apply(to_numeric)`` when values are of type decimal.Decimal. (:issue:`14827`)
11 changes: 11 additions & 0 deletions pandas/tools/tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import locale
import codecs
import nose
import decimal

import numpy as np
from numpy import iinfo
Expand Down Expand Up @@ -208,6 +209,16 @@ def test_numeric(self):
res = to_numeric(s)
tm.assert_series_equal(res, expected)

# GH 14827
df = pd.DataFrame(dict(
a=[1.2, decimal.Decimal(3.14), decimal.Decimal("infinity"), '0.1']
))
df['a'] = df['a'].apply(to_numeric)
expected = pd.DataFrame(dict(
a=[1.2, 3.14, np.inf, 0.1]
))
tm.assert_frame_equal(df, expected)

def test_all_nan(self):
s = pd.Series(['a', 'b', 'c'])
res = to_numeric(s, errors='coerce')
Expand Down
3 changes: 3 additions & 0 deletions pandas/tools/util.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from decimal import Decimal
import numpy as np
import pandas.lib as lib

Expand Down Expand Up @@ -173,6 +174,8 @@ def to_numeric(arg, errors='raise', downcast=None):
values = arg.values
elif isinstance(arg, (list, tuple)):
values = np.array(arg, dtype='O')
elif isinstance(arg, Decimal):
return float(arg)
elif np.isscalar(arg):
if is_number(arg):
return arg
Expand Down