Skip to content

Commit 2d2488c

Browse files
author
Roger Thomas
committed
Fix To Numeric on Decimal Fields
1 parent 5f057cb commit 2d2488c

File tree

4 files changed

+30
-0
lines changed

4 files changed

+30
-0
lines changed

doc/source/whatsnew/v0.20.0.txt

+2
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,5 @@ Performance Improvements
109109

110110
Bug Fixes
111111
~~~~~~~~~
112+
113+
- Bug in ``DataFrame(..).apply(to_numeric)`` when values are of type decimal.Decimal. (:issue:`14827`)

pandas/src/inference.pyx

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from decimal import Decimal
12
import sys
23
cimport util
34
from tslib import NaT, get_timezone
@@ -673,6 +674,9 @@ def maybe_convert_numeric(object[:] values, set na_values,
673674
elif util.is_complex_object(val):
674675
complexes[i] = val
675676
seen_complex = True
677+
elif isinstance(val, Decimal):
678+
floats[i] = complexes[i] = val
679+
seen_float = True
676680
else:
677681
try:
678682
status = floatify(val, &fval, &maybe_int)

pandas/tools/tests/test_util.py

+21
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import locale
33
import codecs
44
import nose
5+
import decimal
56

67
import numpy as np
78
from numpy import iinfo
@@ -208,6 +209,26 @@ def test_numeric(self):
208209
res = to_numeric(s)
209210
tm.assert_series_equal(res, expected)
210211

212+
# GH 14827
213+
df = pd.DataFrame(dict(
214+
a=[1.2, decimal.Decimal(3.14), decimal.Decimal("infinity"), '0.1'],
215+
b=[1.0, 2.0, 3.0, 4.0],
216+
))
217+
expected = pd.DataFrame(dict(
218+
a=[1.2, 3.14, np.inf, 0.1],
219+
b=[1.0, 2.0, 3.0, 4.0],
220+
))
221+
222+
# Test to_numeric over one column
223+
df_copy = df.copy()
224+
df_copy['a'] = df_copy['a'].apply(to_numeric)
225+
tm.assert_frame_equal(df_copy, expected)
226+
227+
# Test to_numeric over multiple columns
228+
df_copy = df.copy()
229+
df_copy[['a', 'b']] = df_copy[['a', 'b']].apply(to_numeric)
230+
tm.assert_frame_equal(df_copy, expected)
231+
211232
def test_all_nan(self):
212233
s = pd.Series(['a', 'b', 'c'])
213234
res = to_numeric(s, errors='coerce')

pandas/tools/util.py

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from decimal import Decimal
12
import numpy as np
23
import pandas.lib as lib
34

@@ -173,6 +174,8 @@ def to_numeric(arg, errors='raise', downcast=None):
173174
values = arg.values
174175
elif isinstance(arg, (list, tuple)):
175176
values = np.array(arg, dtype='O')
177+
elif isinstance(arg, Decimal):
178+
return float(arg)
176179
elif np.isscalar(arg):
177180
if is_number(arg):
178181
return arg

0 commit comments

Comments
 (0)