test_nanops.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. from functools import partial
  2. import operator
  3. import warnings
  4. import numpy as np
  5. import pytest
  6. import pandas.util._test_decorators as td
  7. from pandas.core.dtypes.common import is_integer_dtype
  8. import pandas as pd
  9. from pandas import Series, isna
  10. import pandas._testing as tm
  11. from pandas.core.arrays import DatetimeArray
  12. import pandas.core.nanops as nanops
  13. use_bn = nanops._USE_BOTTLENECK
  14. has_c16 = hasattr(np, "complex128")
  15. class TestnanopsDataFrame:
  16. def setup_method(self, method):
  17. np.random.seed(11235)
  18. nanops._USE_BOTTLENECK = False
  19. arr_shape = (11, 7)
  20. self.arr_float = np.random.randn(*arr_shape)
  21. self.arr_float1 = np.random.randn(*arr_shape)
  22. self.arr_complex = self.arr_float + self.arr_float1 * 1j
  23. self.arr_int = np.random.randint(-10, 10, arr_shape)
  24. self.arr_bool = np.random.randint(0, 2, arr_shape) == 0
  25. self.arr_str = np.abs(self.arr_float).astype("S")
  26. self.arr_utf = np.abs(self.arr_float).astype("U")
  27. self.arr_date = np.random.randint(0, 20000, arr_shape).astype("M8[ns]")
  28. self.arr_tdelta = np.random.randint(0, 20000, arr_shape).astype("m8[ns]")
  29. self.arr_nan = np.tile(np.nan, arr_shape)
  30. self.arr_float_nan = np.vstack([self.arr_float, self.arr_nan])
  31. self.arr_float1_nan = np.vstack([self.arr_float1, self.arr_nan])
  32. self.arr_nan_float1 = np.vstack([self.arr_nan, self.arr_float1])
  33. self.arr_nan_nan = np.vstack([self.arr_nan, self.arr_nan])
  34. self.arr_inf = self.arr_float * np.inf
  35. self.arr_float_inf = np.vstack([self.arr_float, self.arr_inf])
  36. self.arr_nan_inf = np.vstack([self.arr_nan, self.arr_inf])
  37. self.arr_float_nan_inf = np.vstack([self.arr_float, self.arr_nan, self.arr_inf])
  38. self.arr_nan_nan_inf = np.vstack([self.arr_nan, self.arr_nan, self.arr_inf])
  39. self.arr_obj = np.vstack(
  40. [
  41. self.arr_float.astype("O"),
  42. self.arr_int.astype("O"),
  43. self.arr_bool.astype("O"),
  44. self.arr_complex.astype("O"),
  45. self.arr_str.astype("O"),
  46. self.arr_utf.astype("O"),
  47. self.arr_date.astype("O"),
  48. self.arr_tdelta.astype("O"),
  49. ]
  50. )
  51. with np.errstate(invalid="ignore"):
  52. self.arr_nan_nanj = self.arr_nan + self.arr_nan * 1j
  53. self.arr_complex_nan = np.vstack([self.arr_complex, self.arr_nan_nanj])
  54. self.arr_nan_infj = self.arr_inf * 1j
  55. self.arr_complex_nan_infj = np.vstack([self.arr_complex, self.arr_nan_infj])
  56. self.arr_float_2d = self.arr_float
  57. self.arr_float1_2d = self.arr_float1
  58. self.arr_nan_2d = self.arr_nan
  59. self.arr_float_nan_2d = self.arr_float_nan
  60. self.arr_float1_nan_2d = self.arr_float1_nan
  61. self.arr_nan_float1_2d = self.arr_nan_float1
  62. self.arr_float_1d = self.arr_float[:, 0]
  63. self.arr_float1_1d = self.arr_float1[:, 0]
  64. self.arr_nan_1d = self.arr_nan[:, 0]
  65. self.arr_float_nan_1d = self.arr_float_nan[:, 0]
  66. self.arr_float1_nan_1d = self.arr_float1_nan[:, 0]
  67. self.arr_nan_float1_1d = self.arr_nan_float1[:, 0]
  68. def teardown_method(self, method):
  69. nanops._USE_BOTTLENECK = use_bn
  70. def check_results(self, targ, res, axis, check_dtype=True):
  71. res = getattr(res, "asm8", res)
  72. res = getattr(res, "values", res)
  73. # timedeltas are a beast here
  74. def _coerce_tds(targ, res):
  75. if hasattr(targ, "dtype") and targ.dtype == "m8[ns]":
  76. if len(targ) == 1:
  77. targ = targ[0].item()
  78. res = res.item()
  79. else:
  80. targ = targ.view("i8")
  81. return targ, res
  82. try:
  83. if (
  84. axis != 0
  85. and hasattr(targ, "shape")
  86. and targ.ndim
  87. and targ.shape != res.shape
  88. ):
  89. res = np.split(res, [targ.shape[0]], axis=0)[0]
  90. except (ValueError, IndexError):
  91. targ, res = _coerce_tds(targ, res)
  92. try:
  93. tm.assert_almost_equal(targ, res, check_dtype=check_dtype)
  94. except AssertionError:
  95. # handle timedelta dtypes
  96. if hasattr(targ, "dtype") and targ.dtype == "m8[ns]":
  97. targ, res = _coerce_tds(targ, res)
  98. tm.assert_almost_equal(targ, res, check_dtype=check_dtype)
  99. return
  100. # There are sometimes rounding errors with
  101. # complex and object dtypes.
  102. # If it isn't one of those, re-raise the error.
  103. if not hasattr(res, "dtype") or res.dtype.kind not in ["c", "O"]:
  104. raise
  105. # convert object dtypes to something that can be split into
  106. # real and imaginary parts
  107. if res.dtype.kind == "O":
  108. if targ.dtype.kind != "O":
  109. res = res.astype(targ.dtype)
  110. else:
  111. cast_dtype = "c16" if has_c16 else "f8"
  112. res = res.astype(cast_dtype)
  113. targ = targ.astype(cast_dtype)
  114. # there should never be a case where numpy returns an object
  115. # but nanops doesn't, so make that an exception
  116. elif targ.dtype.kind == "O":
  117. raise
  118. tm.assert_almost_equal(np.real(targ), np.real(res), check_dtype=check_dtype)
  119. tm.assert_almost_equal(np.imag(targ), np.imag(res), check_dtype=check_dtype)
  120. def check_fun_data(
  121. self,
  122. testfunc,
  123. targfunc,
  124. testarval,
  125. targarval,
  126. check_dtype=True,
  127. empty_targfunc=None,
  128. **kwargs,
  129. ):
  130. for axis in list(range(targarval.ndim)) + [None]:
  131. for skipna in [False, True]:
  132. targartempval = targarval if skipna else testarval
  133. if skipna and empty_targfunc and isna(targartempval).all():
  134. targ = empty_targfunc(targartempval, axis=axis, **kwargs)
  135. else:
  136. targ = targfunc(targartempval, axis=axis, **kwargs)
  137. res = testfunc(testarval, axis=axis, skipna=skipna, **kwargs)
  138. self.check_results(targ, res, axis, check_dtype=check_dtype)
  139. if skipna:
  140. res = testfunc(testarval, axis=axis, **kwargs)
  141. self.check_results(targ, res, axis, check_dtype=check_dtype)
  142. if axis is None:
  143. res = testfunc(testarval, skipna=skipna, **kwargs)
  144. self.check_results(targ, res, axis, check_dtype=check_dtype)
  145. if skipna and axis is None:
  146. res = testfunc(testarval, **kwargs)
  147. self.check_results(targ, res, axis, check_dtype=check_dtype)
  148. if testarval.ndim <= 1:
  149. return
  150. # Recurse on lower-dimension
  151. testarval2 = np.take(testarval, 0, axis=-1)
  152. targarval2 = np.take(targarval, 0, axis=-1)
  153. self.check_fun_data(
  154. testfunc,
  155. targfunc,
  156. testarval2,
  157. targarval2,
  158. check_dtype=check_dtype,
  159. empty_targfunc=empty_targfunc,
  160. **kwargs,
  161. )
  162. def check_fun(self, testfunc, targfunc, testar, empty_targfunc=None, **kwargs):
  163. targar = testar
  164. if testar.endswith("_nan") and hasattr(self, testar[:-4]):
  165. targar = testar[:-4]
  166. testarval = getattr(self, testar)
  167. targarval = getattr(self, targar)
  168. self.check_fun_data(
  169. testfunc,
  170. targfunc,
  171. testarval,
  172. targarval,
  173. empty_targfunc=empty_targfunc,
  174. **kwargs,
  175. )
  176. def check_funs(
  177. self,
  178. testfunc,
  179. targfunc,
  180. allow_complex=True,
  181. allow_all_nan=True,
  182. allow_date=True,
  183. allow_tdelta=True,
  184. allow_obj=True,
  185. **kwargs,
  186. ):
  187. self.check_fun(testfunc, targfunc, "arr_float", **kwargs)
  188. self.check_fun(testfunc, targfunc, "arr_float_nan", **kwargs)
  189. self.check_fun(testfunc, targfunc, "arr_int", **kwargs)
  190. self.check_fun(testfunc, targfunc, "arr_bool", **kwargs)
  191. objs = [
  192. self.arr_float.astype("O"),
  193. self.arr_int.astype("O"),
  194. self.arr_bool.astype("O"),
  195. ]
  196. if allow_all_nan:
  197. self.check_fun(testfunc, targfunc, "arr_nan", **kwargs)
  198. if allow_complex:
  199. self.check_fun(testfunc, targfunc, "arr_complex", **kwargs)
  200. self.check_fun(testfunc, targfunc, "arr_complex_nan", **kwargs)
  201. if allow_all_nan:
  202. self.check_fun(testfunc, targfunc, "arr_nan_nanj", **kwargs)
  203. objs += [self.arr_complex.astype("O")]
  204. if allow_date:
  205. targfunc(self.arr_date)
  206. self.check_fun(testfunc, targfunc, "arr_date", **kwargs)
  207. objs += [self.arr_date.astype("O")]
  208. if allow_tdelta:
  209. try:
  210. targfunc(self.arr_tdelta)
  211. except TypeError:
  212. pass
  213. else:
  214. self.check_fun(testfunc, targfunc, "arr_tdelta", **kwargs)
  215. objs += [self.arr_tdelta.astype("O")]
  216. if allow_obj:
  217. self.arr_obj = np.vstack(objs)
  218. # some nanops handle object dtypes better than their numpy
  219. # counterparts, so the numpy functions need to be given something
  220. # else
  221. if allow_obj == "convert":
  222. targfunc = partial(
  223. self._badobj_wrap, func=targfunc, allow_complex=allow_complex
  224. )
  225. self.check_fun(testfunc, targfunc, "arr_obj", **kwargs)
  226. def _badobj_wrap(self, value, func, allow_complex=True, **kwargs):
  227. if value.dtype.kind == "O":
  228. if allow_complex:
  229. value = value.astype("c16")
  230. else:
  231. value = value.astype("f8")
  232. return func(value, **kwargs)
  233. @pytest.mark.parametrize(
  234. "nan_op,np_op", [(nanops.nanany, np.any), (nanops.nanall, np.all)]
  235. )
  236. def test_nan_funcs(self, nan_op, np_op):
  237. # TODO: allow tdelta, doesn't break tests
  238. self.check_funs(
  239. nan_op, np_op, allow_all_nan=False, allow_date=False, allow_tdelta=False
  240. )
  241. def test_nansum(self):
  242. self.check_funs(
  243. nanops.nansum,
  244. np.sum,
  245. allow_date=False,
  246. check_dtype=False,
  247. empty_targfunc=np.nansum,
  248. )
  249. def test_nanmean(self):
  250. self.check_funs(
  251. nanops.nanmean,
  252. np.mean,
  253. allow_complex=False, # TODO: allow this, doesn't break test
  254. allow_obj=False,
  255. allow_date=False,
  256. )
  257. def test_nanmean_overflow(self):
  258. # GH 10155
  259. # In the previous implementation mean can overflow for int dtypes, it
  260. # is now consistent with numpy
  261. for a in [2 ** 55, -(2 ** 55), 20150515061816532]:
  262. s = Series(a, index=range(500), dtype=np.int64)
  263. result = s.mean()
  264. np_result = s.values.mean()
  265. assert result == a
  266. assert result == np_result
  267. assert result.dtype == np.float64
  268. @pytest.mark.parametrize(
  269. "dtype",
  270. [
  271. np.int16,
  272. np.int32,
  273. np.int64,
  274. np.float32,
  275. np.float64,
  276. getattr(np, "float128", None),
  277. ],
  278. )
  279. def test_returned_dtype(self, dtype):
  280. if dtype is None:
  281. # no float128 available
  282. return
  283. s = Series(range(10), dtype=dtype)
  284. group_a = ["mean", "std", "var", "skew", "kurt"]
  285. group_b = ["min", "max"]
  286. for method in group_a + group_b:
  287. result = getattr(s, method)()
  288. if is_integer_dtype(dtype) and method in group_a:
  289. assert result.dtype == np.float64
  290. else:
  291. assert result.dtype == dtype
  292. def test_nanmedian(self):
  293. with warnings.catch_warnings(record=True):
  294. warnings.simplefilter("ignore", RuntimeWarning)
  295. self.check_funs(
  296. nanops.nanmedian,
  297. np.median,
  298. allow_complex=False,
  299. allow_date=False,
  300. allow_obj="convert",
  301. )
  302. @pytest.mark.parametrize("ddof", range(3))
  303. def test_nanvar(self, ddof):
  304. self.check_funs(
  305. nanops.nanvar,
  306. np.var,
  307. allow_complex=False,
  308. allow_date=False,
  309. allow_obj="convert",
  310. ddof=ddof,
  311. )
  312. @pytest.mark.parametrize("ddof", range(3))
  313. def test_nanstd(self, ddof):
  314. self.check_funs(
  315. nanops.nanstd,
  316. np.std,
  317. allow_complex=False,
  318. allow_date=False,
  319. allow_obj="convert",
  320. ddof=ddof,
  321. )
  322. @td.skip_if_no_scipy
  323. @pytest.mark.parametrize("ddof", range(3))
  324. def test_nansem(self, ddof):
  325. from scipy.stats import sem
  326. with np.errstate(invalid="ignore"):
  327. self.check_funs(
  328. nanops.nansem,
  329. sem,
  330. allow_complex=False,
  331. allow_date=False,
  332. allow_tdelta=False,
  333. allow_obj="convert",
  334. ddof=ddof,
  335. )
  336. @pytest.mark.parametrize(
  337. "nan_op,np_op", [(nanops.nanmin, np.min), (nanops.nanmax, np.max)]
  338. )
  339. def test_nanops_with_warnings(self, nan_op, np_op):
  340. with warnings.catch_warnings(record=True):
  341. warnings.simplefilter("ignore", RuntimeWarning)
  342. self.check_funs(nan_op, np_op, allow_obj=False)
  343. def _argminmax_wrap(self, value, axis=None, func=None):
  344. res = func(value, axis)
  345. nans = np.min(value, axis)
  346. nullnan = isna(nans)
  347. if res.ndim:
  348. res[nullnan] = -1
  349. elif (
  350. hasattr(nullnan, "all")
  351. and nullnan.all()
  352. or not hasattr(nullnan, "all")
  353. and nullnan
  354. ):
  355. res = -1
  356. return res
  357. def test_nanargmax(self):
  358. with warnings.catch_warnings(record=True):
  359. warnings.simplefilter("ignore", RuntimeWarning)
  360. func = partial(self._argminmax_wrap, func=np.argmax)
  361. self.check_funs(nanops.nanargmax, func, allow_obj=False)
  362. def test_nanargmin(self):
  363. with warnings.catch_warnings(record=True):
  364. warnings.simplefilter("ignore", RuntimeWarning)
  365. func = partial(self._argminmax_wrap, func=np.argmin)
  366. self.check_funs(nanops.nanargmin, func, allow_obj=False)
  367. def _skew_kurt_wrap(self, values, axis=None, func=None):
  368. if not isinstance(values.dtype.type, np.floating):
  369. values = values.astype("f8")
  370. result = func(values, axis=axis, bias=False)
  371. # fix for handling cases where all elements in an axis are the same
  372. if isinstance(result, np.ndarray):
  373. result[np.max(values, axis=axis) == np.min(values, axis=axis)] = 0
  374. return result
  375. elif np.max(values) == np.min(values):
  376. return 0.0
  377. return result
  378. @td.skip_if_no_scipy
  379. def test_nanskew(self):
  380. from scipy.stats import skew
  381. func = partial(self._skew_kurt_wrap, func=skew)
  382. with np.errstate(invalid="ignore"):
  383. self.check_funs(
  384. nanops.nanskew,
  385. func,
  386. allow_complex=False,
  387. allow_date=False,
  388. allow_tdelta=False,
  389. )
  390. @td.skip_if_no_scipy
  391. def test_nankurt(self):
  392. from scipy.stats import kurtosis
  393. func1 = partial(kurtosis, fisher=True)
  394. func = partial(self._skew_kurt_wrap, func=func1)
  395. with np.errstate(invalid="ignore"):
  396. self.check_funs(
  397. nanops.nankurt,
  398. func,
  399. allow_complex=False,
  400. allow_date=False,
  401. allow_tdelta=False,
  402. )
  403. def test_nanprod(self):
  404. self.check_funs(
  405. nanops.nanprod,
  406. np.prod,
  407. allow_date=False,
  408. allow_tdelta=False,
  409. empty_targfunc=np.nanprod,
  410. )
  411. def check_nancorr_nancov_2d(self, checkfun, targ0, targ1, **kwargs):
  412. res00 = checkfun(self.arr_float_2d, self.arr_float1_2d, **kwargs)
  413. res01 = checkfun(
  414. self.arr_float_2d,
  415. self.arr_float1_2d,
  416. min_periods=len(self.arr_float_2d) - 1,
  417. **kwargs,
  418. )
  419. tm.assert_almost_equal(targ0, res00)
  420. tm.assert_almost_equal(targ0, res01)
  421. res10 = checkfun(self.arr_float_nan_2d, self.arr_float1_nan_2d, **kwargs)
  422. res11 = checkfun(
  423. self.arr_float_nan_2d,
  424. self.arr_float1_nan_2d,
  425. min_periods=len(self.arr_float_2d) - 1,
  426. **kwargs,
  427. )
  428. tm.assert_almost_equal(targ1, res10)
  429. tm.assert_almost_equal(targ1, res11)
  430. targ2 = np.nan
  431. res20 = checkfun(self.arr_nan_2d, self.arr_float1_2d, **kwargs)
  432. res21 = checkfun(self.arr_float_2d, self.arr_nan_2d, **kwargs)
  433. res22 = checkfun(self.arr_nan_2d, self.arr_nan_2d, **kwargs)
  434. res23 = checkfun(self.arr_float_nan_2d, self.arr_nan_float1_2d, **kwargs)
  435. res24 = checkfun(
  436. self.arr_float_nan_2d,
  437. self.arr_nan_float1_2d,
  438. min_periods=len(self.arr_float_2d) - 1,
  439. **kwargs,
  440. )
  441. res25 = checkfun(
  442. self.arr_float_2d,
  443. self.arr_float1_2d,
  444. min_periods=len(self.arr_float_2d) + 1,
  445. **kwargs,
  446. )
  447. tm.assert_almost_equal(targ2, res20)
  448. tm.assert_almost_equal(targ2, res21)
  449. tm.assert_almost_equal(targ2, res22)
  450. tm.assert_almost_equal(targ2, res23)
  451. tm.assert_almost_equal(targ2, res24)
  452. tm.assert_almost_equal(targ2, res25)
  453. def check_nancorr_nancov_1d(self, checkfun, targ0, targ1, **kwargs):
  454. res00 = checkfun(self.arr_float_1d, self.arr_float1_1d, **kwargs)
  455. res01 = checkfun(
  456. self.arr_float_1d,
  457. self.arr_float1_1d,
  458. min_periods=len(self.arr_float_1d) - 1,
  459. **kwargs,
  460. )
  461. tm.assert_almost_equal(targ0, res00)
  462. tm.assert_almost_equal(targ0, res01)
  463. res10 = checkfun(self.arr_float_nan_1d, self.arr_float1_nan_1d, **kwargs)
  464. res11 = checkfun(
  465. self.arr_float_nan_1d,
  466. self.arr_float1_nan_1d,
  467. min_periods=len(self.arr_float_1d) - 1,
  468. **kwargs,
  469. )
  470. tm.assert_almost_equal(targ1, res10)
  471. tm.assert_almost_equal(targ1, res11)
  472. targ2 = np.nan
  473. res20 = checkfun(self.arr_nan_1d, self.arr_float1_1d, **kwargs)
  474. res21 = checkfun(self.arr_float_1d, self.arr_nan_1d, **kwargs)
  475. res22 = checkfun(self.arr_nan_1d, self.arr_nan_1d, **kwargs)
  476. res23 = checkfun(self.arr_float_nan_1d, self.arr_nan_float1_1d, **kwargs)
  477. res24 = checkfun(
  478. self.arr_float_nan_1d,
  479. self.arr_nan_float1_1d,
  480. min_periods=len(self.arr_float_1d) - 1,
  481. **kwargs,
  482. )
  483. res25 = checkfun(
  484. self.arr_float_1d,
  485. self.arr_float1_1d,
  486. min_periods=len(self.arr_float_1d) + 1,
  487. **kwargs,
  488. )
  489. tm.assert_almost_equal(targ2, res20)
  490. tm.assert_almost_equal(targ2, res21)
  491. tm.assert_almost_equal(targ2, res22)
  492. tm.assert_almost_equal(targ2, res23)
  493. tm.assert_almost_equal(targ2, res24)
  494. tm.assert_almost_equal(targ2, res25)
  495. def test_nancorr(self):
  496. targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1]
  497. targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1]
  498. self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1)
  499. targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1]
  500. targ1 = np.corrcoef(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1]
  501. self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="pearson")
  502. def test_nancorr_pearson(self):
  503. targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1]
  504. targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1]
  505. self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="pearson")
  506. targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1]
  507. targ1 = np.corrcoef(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1]
  508. self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="pearson")
  509. @td.skip_if_no_scipy
  510. def test_nancorr_kendall(self):
  511. from scipy.stats import kendalltau
  512. targ0 = kendalltau(self.arr_float_2d, self.arr_float1_2d)[0]
  513. targ1 = kendalltau(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0]
  514. self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="kendall")
  515. targ0 = kendalltau(self.arr_float_1d, self.arr_float1_1d)[0]
  516. targ1 = kendalltau(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0]
  517. self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="kendall")
  518. @td.skip_if_no_scipy
  519. def test_nancorr_spearman(self):
  520. from scipy.stats import spearmanr
  521. targ0 = spearmanr(self.arr_float_2d, self.arr_float1_2d)[0]
  522. targ1 = spearmanr(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0]
  523. self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="spearman")
  524. targ0 = spearmanr(self.arr_float_1d, self.arr_float1_1d)[0]
  525. targ1 = spearmanr(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0]
  526. self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="spearman")
  527. @td.skip_if_no_scipy
  528. def test_invalid_method(self):
  529. targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1]
  530. targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1]
  531. msg = "Unkown method 'foo', expected one of 'kendall', 'spearman'"
  532. with pytest.raises(ValueError, match=msg):
  533. self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="foo")
  534. def test_nancov(self):
  535. targ0 = np.cov(self.arr_float_2d, self.arr_float1_2d)[0, 1]
  536. targ1 = np.cov(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1]
  537. self.check_nancorr_nancov_2d(nanops.nancov, targ0, targ1)
  538. targ0 = np.cov(self.arr_float_1d, self.arr_float1_1d)[0, 1]
  539. targ1 = np.cov(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1]
  540. self.check_nancorr_nancov_1d(nanops.nancov, targ0, targ1)
  541. def check_nancomp(self, checkfun, targ0):
  542. arr_float = self.arr_float
  543. arr_float1 = self.arr_float1
  544. arr_nan = self.arr_nan
  545. arr_nan_nan = self.arr_nan_nan
  546. arr_float_nan = self.arr_float_nan
  547. arr_float1_nan = self.arr_float1_nan
  548. arr_nan_float1 = self.arr_nan_float1
  549. while targ0.ndim:
  550. res0 = checkfun(arr_float, arr_float1)
  551. tm.assert_almost_equal(targ0, res0)
  552. if targ0.ndim > 1:
  553. targ1 = np.vstack([targ0, arr_nan])
  554. else:
  555. targ1 = np.hstack([targ0, arr_nan])
  556. res1 = checkfun(arr_float_nan, arr_float1_nan)
  557. tm.assert_numpy_array_equal(targ1, res1, check_dtype=False)
  558. targ2 = arr_nan_nan
  559. res2 = checkfun(arr_float_nan, arr_nan_float1)
  560. tm.assert_numpy_array_equal(targ2, res2, check_dtype=False)
  561. # Lower dimension for next step in the loop
  562. arr_float = np.take(arr_float, 0, axis=-1)
  563. arr_float1 = np.take(arr_float1, 0, axis=-1)
  564. arr_nan = np.take(arr_nan, 0, axis=-1)
  565. arr_nan_nan = np.take(arr_nan_nan, 0, axis=-1)
  566. arr_float_nan = np.take(arr_float_nan, 0, axis=-1)
  567. arr_float1_nan = np.take(arr_float1_nan, 0, axis=-1)
  568. arr_nan_float1 = np.take(arr_nan_float1, 0, axis=-1)
  569. targ0 = np.take(targ0, 0, axis=-1)
  570. @pytest.mark.parametrize(
  571. "op,nanop",
  572. [
  573. (operator.eq, nanops.naneq),
  574. (operator.ne, nanops.nanne),
  575. (operator.gt, nanops.nangt),
  576. (operator.ge, nanops.nange),
  577. (operator.lt, nanops.nanlt),
  578. (operator.le, nanops.nanle),
  579. ],
  580. )
  581. def test_nan_comparison(self, op, nanop):
  582. targ0 = op(self.arr_float, self.arr_float1)
  583. self.check_nancomp(nanop, targ0)
  584. def check_bool(self, func, value, correct):
  585. while getattr(value, "ndim", True):
  586. res0 = func(value)
  587. if correct:
  588. assert res0
  589. else:
  590. assert not res0
  591. if not hasattr(value, "ndim"):
  592. break
  593. # Reduce dimension for next step in the loop
  594. value = np.take(value, 0, axis=-1)
  595. def test__has_infs(self):
  596. pairs = [
  597. ("arr_complex", False),
  598. ("arr_int", False),
  599. ("arr_bool", False),
  600. ("arr_str", False),
  601. ("arr_utf", False),
  602. ("arr_complex", False),
  603. ("arr_complex_nan", False),
  604. ("arr_nan_nanj", False),
  605. ("arr_nan_infj", True),
  606. ("arr_complex_nan_infj", True),
  607. ]
  608. pairs_float = [
  609. ("arr_float", False),
  610. ("arr_nan", False),
  611. ("arr_float_nan", False),
  612. ("arr_nan_nan", False),
  613. ("arr_float_inf", True),
  614. ("arr_inf", True),
  615. ("arr_nan_inf", True),
  616. ("arr_float_nan_inf", True),
  617. ("arr_nan_nan_inf", True),
  618. ]
  619. for arr, correct in pairs:
  620. val = getattr(self, arr)
  621. self.check_bool(nanops._has_infs, val, correct)
  622. for arr, correct in pairs_float:
  623. val = getattr(self, arr)
  624. self.check_bool(nanops._has_infs, val, correct)
  625. self.check_bool(nanops._has_infs, val.astype("f4"), correct)
  626. self.check_bool(nanops._has_infs, val.astype("f2"), correct)
  627. def test__bn_ok_dtype(self):
  628. assert nanops._bn_ok_dtype(self.arr_float.dtype, "test")
  629. assert nanops._bn_ok_dtype(self.arr_complex.dtype, "test")
  630. assert nanops._bn_ok_dtype(self.arr_int.dtype, "test")
  631. assert nanops._bn_ok_dtype(self.arr_bool.dtype, "test")
  632. assert nanops._bn_ok_dtype(self.arr_str.dtype, "test")
  633. assert nanops._bn_ok_dtype(self.arr_utf.dtype, "test")
  634. assert not nanops._bn_ok_dtype(self.arr_date.dtype, "test")
  635. assert not nanops._bn_ok_dtype(self.arr_tdelta.dtype, "test")
  636. assert not nanops._bn_ok_dtype(self.arr_obj.dtype, "test")
  637. class TestEnsureNumeric:
  638. def test_numeric_values(self):
  639. # Test integer
  640. assert nanops._ensure_numeric(1) == 1
  641. # Test float
  642. assert nanops._ensure_numeric(1.1) == 1.1
  643. # Test complex
  644. assert nanops._ensure_numeric(1 + 2j) == 1 + 2j
  645. def test_ndarray(self):
  646. # Test numeric ndarray
  647. values = np.array([1, 2, 3])
  648. assert np.allclose(nanops._ensure_numeric(values), values)
  649. # Test object ndarray
  650. o_values = values.astype(object)
  651. assert np.allclose(nanops._ensure_numeric(o_values), values)
  652. # Test convertible string ndarray
  653. s_values = np.array(["1", "2", "3"], dtype=object)
  654. assert np.allclose(nanops._ensure_numeric(s_values), values)
  655. # Test non-convertible string ndarray
  656. s_values = np.array(["foo", "bar", "baz"], dtype=object)
  657. msg = r"could not convert string to float: '(foo|baz)'"
  658. with pytest.raises(ValueError, match=msg):
  659. nanops._ensure_numeric(s_values)
  660. def test_convertable_values(self):
  661. assert np.allclose(nanops._ensure_numeric("1"), 1.0)
  662. assert np.allclose(nanops._ensure_numeric("1.1"), 1.1)
  663. assert np.allclose(nanops._ensure_numeric("1+1j"), 1 + 1j)
  664. def test_non_convertable_values(self):
  665. msg = "Could not convert foo to numeric"
  666. with pytest.raises(TypeError, match=msg):
  667. nanops._ensure_numeric("foo")
  668. # with the wrong type, python raises TypeError for us
  669. msg = "argument must be a string or a number"
  670. with pytest.raises(TypeError, match=msg):
  671. nanops._ensure_numeric({})
  672. with pytest.raises(TypeError, match=msg):
  673. nanops._ensure_numeric([])
  674. class TestNanvarFixedValues:
  675. # xref GH10242
  676. def setup_method(self, method):
  677. # Samples from a normal distribution.
  678. self.variance = variance = 3.0
  679. self.samples = self.prng.normal(scale=variance ** 0.5, size=100000)
  680. def test_nanvar_all_finite(self):
  681. samples = self.samples
  682. actual_variance = nanops.nanvar(samples)
  683. tm.assert_almost_equal(actual_variance, self.variance, check_less_precise=2)
  684. def test_nanvar_nans(self):
  685. samples = np.nan * np.ones(2 * self.samples.shape[0])
  686. samples[::2] = self.samples
  687. actual_variance = nanops.nanvar(samples, skipna=True)
  688. tm.assert_almost_equal(actual_variance, self.variance, check_less_precise=2)
  689. actual_variance = nanops.nanvar(samples, skipna=False)
  690. tm.assert_almost_equal(actual_variance, np.nan, check_less_precise=2)
  691. def test_nanstd_nans(self):
  692. samples = np.nan * np.ones(2 * self.samples.shape[0])
  693. samples[::2] = self.samples
  694. actual_std = nanops.nanstd(samples, skipna=True)
  695. tm.assert_almost_equal(actual_std, self.variance ** 0.5, check_less_precise=2)
  696. actual_std = nanops.nanvar(samples, skipna=False)
  697. tm.assert_almost_equal(actual_std, np.nan, check_less_precise=2)
  698. def test_nanvar_axis(self):
  699. # Generate some sample data.
  700. samples_norm = self.samples
  701. samples_unif = self.prng.uniform(size=samples_norm.shape[0])
  702. samples = np.vstack([samples_norm, samples_unif])
  703. actual_variance = nanops.nanvar(samples, axis=1)
  704. tm.assert_almost_equal(
  705. actual_variance, np.array([self.variance, 1.0 / 12]), check_less_precise=2
  706. )
  707. def test_nanvar_ddof(self):
  708. n = 5
  709. samples = self.prng.uniform(size=(10000, n + 1))
  710. samples[:, -1] = np.nan # Force use of our own algorithm.
  711. variance_0 = nanops.nanvar(samples, axis=1, skipna=True, ddof=0).mean()
  712. variance_1 = nanops.nanvar(samples, axis=1, skipna=True, ddof=1).mean()
  713. variance_2 = nanops.nanvar(samples, axis=1, skipna=True, ddof=2).mean()
  714. # The unbiased estimate.
  715. var = 1.0 / 12
  716. tm.assert_almost_equal(variance_1, var, check_less_precise=2)
  717. # The underestimated variance.
  718. tm.assert_almost_equal(variance_0, (n - 1.0) / n * var, check_less_precise=2)
  719. # The overestimated variance.
  720. tm.assert_almost_equal(
  721. variance_2, (n - 1.0) / (n - 2.0) * var, check_less_precise=2
  722. )
  723. def test_ground_truth(self):
  724. # Test against values that were precomputed with Numpy.
  725. samples = np.empty((4, 4))
  726. samples[:3, :3] = np.array(
  727. [
  728. [0.97303362, 0.21869576, 0.55560287],
  729. [0.72980153, 0.03109364, 0.99155171],
  730. [0.09317602, 0.60078248, 0.15871292],
  731. ]
  732. )
  733. samples[3] = samples[:, 3] = np.nan
  734. # Actual variances along axis=0, 1 for ddof=0, 1, 2
  735. variance = np.array(
  736. [
  737. [
  738. [0.13762259, 0.05619224, 0.11568816],
  739. [0.20643388, 0.08428837, 0.17353224],
  740. [0.41286776, 0.16857673, 0.34706449],
  741. ],
  742. [
  743. [0.09519783, 0.16435395, 0.05082054],
  744. [0.14279674, 0.24653093, 0.07623082],
  745. [0.28559348, 0.49306186, 0.15246163],
  746. ],
  747. ]
  748. )
  749. # Test nanvar.
  750. for axis in range(2):
  751. for ddof in range(3):
  752. var = nanops.nanvar(samples, skipna=True, axis=axis, ddof=ddof)
  753. tm.assert_almost_equal(var[:3], variance[axis, ddof])
  754. assert np.isnan(var[3])
  755. # Test nanstd.
  756. for axis in range(2):
  757. for ddof in range(3):
  758. std = nanops.nanstd(samples, skipna=True, axis=axis, ddof=ddof)
  759. tm.assert_almost_equal(std[:3], variance[axis, ddof] ** 0.5)
  760. assert np.isnan(std[3])
  761. def test_nanstd_roundoff(self):
  762. # Regression test for GH 10242 (test data taken from GH 10489). Ensure
  763. # that variance is stable.
  764. data = Series(766897346 * np.ones(10))
  765. for ddof in range(3):
  766. result = data.std(ddof=ddof)
  767. assert result == 0.0
  768. @property
  769. def prng(self):
  770. return np.random.RandomState(1234)
  771. class TestNanskewFixedValues:
  772. # xref GH 11974
  773. def setup_method(self, method):
  774. # Test data + skewness value (computed with scipy.stats.skew)
  775. self.samples = np.sin(np.linspace(0, 1, 200))
  776. self.actual_skew = -0.1875895205961754
  777. def test_constant_series(self):
  778. # xref GH 11974
  779. for val in [3075.2, 3075.3, 3075.5]:
  780. data = val * np.ones(300)
  781. skew = nanops.nanskew(data)
  782. assert skew == 0.0
  783. def test_all_finite(self):
  784. alpha, beta = 0.3, 0.1
  785. left_tailed = self.prng.beta(alpha, beta, size=100)
  786. assert nanops.nanskew(left_tailed) < 0
  787. alpha, beta = 0.1, 0.3
  788. right_tailed = self.prng.beta(alpha, beta, size=100)
  789. assert nanops.nanskew(right_tailed) > 0
  790. def test_ground_truth(self):
  791. skew = nanops.nanskew(self.samples)
  792. tm.assert_almost_equal(skew, self.actual_skew)
  793. def test_axis(self):
  794. samples = np.vstack([self.samples, np.nan * np.ones(len(self.samples))])
  795. skew = nanops.nanskew(samples, axis=1)
  796. tm.assert_almost_equal(skew, np.array([self.actual_skew, np.nan]))
  797. def test_nans(self):
  798. samples = np.hstack([self.samples, np.nan])
  799. skew = nanops.nanskew(samples, skipna=False)
  800. assert np.isnan(skew)
  801. def test_nans_skipna(self):
  802. samples = np.hstack([self.samples, np.nan])
  803. skew = nanops.nanskew(samples, skipna=True)
  804. tm.assert_almost_equal(skew, self.actual_skew)
  805. @property
  806. def prng(self):
  807. return np.random.RandomState(1234)
  808. class TestNankurtFixedValues:
  809. # xref GH 11974
  810. def setup_method(self, method):
  811. # Test data + kurtosis value (computed with scipy.stats.kurtosis)
  812. self.samples = np.sin(np.linspace(0, 1, 200))
  813. self.actual_kurt = -1.2058303433799713
  814. def test_constant_series(self):
  815. # xref GH 11974
  816. for val in [3075.2, 3075.3, 3075.5]:
  817. data = val * np.ones(300)
  818. kurt = nanops.nankurt(data)
  819. assert kurt == 0.0
  820. def test_all_finite(self):
  821. alpha, beta = 0.3, 0.1
  822. left_tailed = self.prng.beta(alpha, beta, size=100)
  823. assert nanops.nankurt(left_tailed) < 0
  824. alpha, beta = 0.1, 0.3
  825. right_tailed = self.prng.beta(alpha, beta, size=100)
  826. assert nanops.nankurt(right_tailed) > 0
  827. def test_ground_truth(self):
  828. kurt = nanops.nankurt(self.samples)
  829. tm.assert_almost_equal(kurt, self.actual_kurt)
  830. def test_axis(self):
  831. samples = np.vstack([self.samples, np.nan * np.ones(len(self.samples))])
  832. kurt = nanops.nankurt(samples, axis=1)
  833. tm.assert_almost_equal(kurt, np.array([self.actual_kurt, np.nan]))
  834. def test_nans(self):
  835. samples = np.hstack([self.samples, np.nan])
  836. kurt = nanops.nankurt(samples, skipna=False)
  837. assert np.isnan(kurt)
  838. def test_nans_skipna(self):
  839. samples = np.hstack([self.samples, np.nan])
  840. kurt = nanops.nankurt(samples, skipna=True)
  841. tm.assert_almost_equal(kurt, self.actual_kurt)
  842. @property
  843. def prng(self):
  844. return np.random.RandomState(1234)
  845. class TestDatetime64NaNOps:
  846. @pytest.mark.parametrize("tz", [None, "UTC"])
  847. @pytest.mark.xfail(reason="disabled")
  848. # Enabling mean changes the behavior of DataFrame.mean
  849. # See https://github.com/pandas-dev/pandas/issues/24752
  850. def test_nanmean(self, tz):
  851. dti = pd.date_range("2016-01-01", periods=3, tz=tz)
  852. expected = dti[1]
  853. for obj in [dti, DatetimeArray(dti), Series(dti)]:
  854. result = nanops.nanmean(obj)
  855. assert result == expected
  856. dti2 = dti.insert(1, pd.NaT)
  857. for obj in [dti2, DatetimeArray(dti2), Series(dti2)]:
  858. result = nanops.nanmean(obj)
  859. assert result == expected
  860. def test_use_bottleneck():
  861. if nanops._BOTTLENECK_INSTALLED:
  862. pd.set_option("use_bottleneck", True)
  863. assert pd.get_option("use_bottleneck")
  864. pd.set_option("use_bottleneck", False)
  865. assert not pd.get_option("use_bottleneck")
  866. pd.set_option("use_bottleneck", use_bn)
  867. @pytest.mark.parametrize(
  868. "numpy_op, expected",
  869. [
  870. (np.sum, 10),
  871. (np.nansum, 10),
  872. (np.mean, 2.5),
  873. (np.nanmean, 2.5),
  874. (np.median, 2.5),
  875. (np.nanmedian, 2.5),
  876. (np.min, 1),
  877. (np.max, 4),
  878. (np.nanmin, 1),
  879. (np.nanmax, 4),
  880. ],
  881. )
  882. def test_numpy_ops(numpy_op, expected):
  883. # GH8383
  884. result = numpy_op(pd.Series([1, 2, 3, 4]))
  885. assert result == expected
  886. @pytest.mark.parametrize(
  887. "operation",
  888. [
  889. nanops.nanany,
  890. nanops.nanall,
  891. nanops.nansum,
  892. nanops.nanmean,
  893. nanops.nanmedian,
  894. nanops.nanstd,
  895. nanops.nanvar,
  896. nanops.nansem,
  897. nanops.nanargmax,
  898. nanops.nanargmin,
  899. nanops.nanmax,
  900. nanops.nanmin,
  901. nanops.nanskew,
  902. nanops.nankurt,
  903. nanops.nanprod,
  904. ],
  905. )
  906. def test_nanops_independent_of_mask_param(operation):
  907. # GH22764
  908. s = pd.Series([1, 2, np.nan, 3, np.nan, 4])
  909. mask = s.isna()
  910. median_expected = operation(s)
  911. median_result = operation(s, mask=mask)
  912. assert median_expected == median_result