Skip to content

Commit f9dd1ae

Browse files
adamkleinwesm
authored andcommitted
ENH: add parameter to nancorr to suppress div by zero
1 parent 56a77f3 commit f9dd1ae

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

pandas/src/moments.pyx

+8-3
Original file line numberDiff line numberDiff line change
@@ -252,13 +252,13 @@ def ewma(ndarray[double_t] input, double_t com):
252252

253253
@cython.boundscheck(False)
254254
@cython.wraparound(False)
255-
def nancorr(ndarray[float64_t, ndim=2] mat):
255+
def nancorr(ndarray[float64_t, ndim=2] mat, na_ok=False):
256256
cdef:
257257
Py_ssize_t i, j, xi, yi, N, K
258258
ndarray[float64_t, ndim=2] result
259259
ndarray[uint8_t, ndim=2] mask
260260
int64_t nobs = 0
261-
float64_t vx, vy, sumx, sumy, sumxx, sumyy, meanx, meany
261+
float64_t vx, vy, sumx, sumy, sumxx, sumyy, meanx, meany, divisor
262262

263263
N, K = (<object> mat).shape
264264

@@ -291,7 +291,12 @@ def nancorr(ndarray[float64_t, ndim=2] mat):
291291
sumxx += vx * vx
292292
sumyy += vy * vy
293293

294-
result[xi, yi] = result[yi, xi] = sumx / sqrt(sumxx * sumyy)
294+
divisor = sqrt(sumxx * sumyy)
295+
296+
if na_ok == 0:
297+
result[xi, yi] = result[yi, xi] = sumx / divisor if divisor != 0 else np.NaN
298+
else:
299+
result[xi, yi] = result[yi, xi] = sumx / divisor
295300

296301
return result
297302

0 commit comments

Comments
 (0)