3
3
import numpy as np
4
4
5
5
from pandas .core .common import isnull , notnull
6
+ import pandas .core .common as com
6
7
import pandas ._tseries as lib
7
8
8
9
try :
@@ -18,7 +19,7 @@ def _bottleneck_switch(bn_name, alt, **kwargs):
18
19
bn_func = None
19
20
def f (values , axis = None , skipna = True ):
20
21
try :
21
- if _USE_BOTTLENECK and skipna :
22
+ if _USE_BOTTLENECK and skipna and values . dtype != np . object_ :
22
23
result = bn_func (values , axis = axis , ** kwargs )
23
24
# prefer to treat inf/-inf as NA
24
25
if _has_infs (result ):
@@ -62,7 +63,7 @@ def _nanmean(values, axis=None, skipna=True):
62
63
values = values .copy ()
63
64
np .putmask (values , mask , 0 )
64
65
65
- the_sum = values .sum (axis )
66
+ the_sum = _ensure_numeric ( values .sum (axis ) )
66
67
count = _get_counts (mask , axis )
67
68
68
69
if axis is not None :
@@ -101,8 +102,8 @@ def _nanvar(values, axis=None, skipna=True, ddof=1):
101
102
values = values .copy ()
102
103
np .putmask (values , mask , 0 )
103
104
104
- X = values .sum (axis )
105
- XX = ( values ** 2 ).sum (axis )
105
+ X = _ensure_numeric ( values .sum (axis ) )
106
+ XX = _ensure_numeric (( values ** 2 ).sum (axis ) )
106
107
return (XX - X ** 2 / count ) / (count - ddof )
107
108
108
109
def _nanmin (values , axis = None , skipna = True ):
@@ -307,6 +308,18 @@ def nancov(a, b):
307
308
308
309
return np .cov (a , b )[0 , 1 ]
309
310
311
+ def _ensure_numeric (x ):
312
+ if isinstance (x , np .ndarray ):
313
+ if x .dtype == np .object_ :
314
+ x = x .astype (np .float64 )
315
+ elif not (com .is_float (x ) or com .is_integer (x )):
316
+ try :
317
+ x = float (x )
318
+ except Exception :
319
+ raise TypeError ('Could not convert %s to numeric' % str (x ))
320
+
321
+ return x
322
+
310
323
# NA-friendly array comparisons
311
324
312
325
import operator
0 commit comments