missing.pyx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. from decimal import Decimal
  2. import numbers
  3. from sys import maxsize
  4. cimport cython
  5. from cpython.datetime cimport (
  6. date,
  7. time,
  8. timedelta,
  9. )
  10. from cython cimport Py_ssize_t
  11. import numpy as np
  12. cimport numpy as cnp
  13. from numpy cimport (
  14. flatiter,
  15. float64_t,
  16. int64_t,
  17. ndarray,
  18. uint8_t,
  19. )
  20. cnp.import_array()
  21. from pandas._libs cimport util
  22. from pandas._libs.tslibs.nattype cimport (
  23. c_NaT as NaT,
  24. checknull_with_nat,
  25. is_dt64nat,
  26. is_td64nat,
  27. )
  28. from pandas._libs.tslibs.np_datetime cimport (
  29. get_datetime64_unit,
  30. get_datetime64_value,
  31. get_timedelta64_value,
  32. )
  33. from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op
  34. cdef:
  35. float64_t INF = <float64_t>np.inf
  36. float64_t NEGINF = -INF
  37. int64_t NPY_NAT = util.get_nat()
  38. bint is_32bit = maxsize <= 2 ** 32
  39. type cDecimal = Decimal # for faster isinstance checks
  40. cpdef bint check_na_tuples_nonequal(object left, object right):
  41. """
  42. When we have NA in one of the tuples but not the other we have to check here,
  43. because our regular checks fail before with ambigous boolean value.
  44. Parameters
  45. ----------
  46. left: Any
  47. right: Any
  48. Returns
  49. -------
  50. True if we are dealing with tuples that have NA on one side and non NA on
  51. the other side.
  52. """
  53. if not isinstance(left, tuple) or not isinstance(right, tuple):
  54. return False
  55. if len(left) != len(right):
  56. return False
  57. for left_element, right_element in zip(left, right):
  58. if left_element is C_NA and right_element is not C_NA:
  59. return True
  60. elif right_element is C_NA and left_element is not C_NA:
  61. return True
  62. return False
  63. cpdef bint is_matching_na(object left, object right, bint nan_matches_none=False):
  64. """
  65. Check if two scalars are both NA of matching types.
  66. Parameters
  67. ----------
  68. left : Any
  69. right : Any
  70. nan_matches_none : bool, default False
  71. For backwards compatibility, consider NaN as matching None.
  72. Returns
  73. -------
  74. bool
  75. """
  76. if left is None:
  77. if nan_matches_none and util.is_nan(right):
  78. return True
  79. return right is None
  80. elif left is C_NA:
  81. return right is C_NA
  82. elif left is NaT:
  83. return right is NaT
  84. elif util.is_float_object(left):
  85. if nan_matches_none and right is None and util.is_nan(left):
  86. return True
  87. return (
  88. util.is_nan(left)
  89. and util.is_float_object(right)
  90. and util.is_nan(right)
  91. )
  92. elif util.is_complex_object(left):
  93. return (
  94. util.is_nan(left)
  95. and util.is_complex_object(right)
  96. and util.is_nan(right)
  97. )
  98. elif util.is_datetime64_object(left):
  99. return (
  100. get_datetime64_value(left) == NPY_NAT
  101. and util.is_datetime64_object(right)
  102. and get_datetime64_value(right) == NPY_NAT
  103. and get_datetime64_unit(left) == get_datetime64_unit(right)
  104. )
  105. elif util.is_timedelta64_object(left):
  106. return (
  107. get_timedelta64_value(left) == NPY_NAT
  108. and util.is_timedelta64_object(right)
  109. and get_timedelta64_value(right) == NPY_NAT
  110. and get_datetime64_unit(left) == get_datetime64_unit(right)
  111. )
  112. elif is_decimal_na(left):
  113. return is_decimal_na(right)
  114. return False
  115. cpdef bint checknull(object val, bint inf_as_na=False):
  116. """
  117. Return boolean describing of the input is NA-like, defined here as any
  118. of:
  119. - None
  120. - nan
  121. - NaT
  122. - np.datetime64 representation of NaT
  123. - np.timedelta64 representation of NaT
  124. - NA
  125. - Decimal("NaN")
  126. Parameters
  127. ----------
  128. val : object
  129. inf_as_na : bool, default False
  130. Whether to treat INF and -INF as NA values.
  131. Returns
  132. -------
  133. bool
  134. """
  135. if val is None or val is NaT or val is C_NA:
  136. return True
  137. elif util.is_float_object(val) or util.is_complex_object(val):
  138. if val != val:
  139. return True
  140. elif inf_as_na:
  141. return val == INF or val == NEGINF
  142. return False
  143. elif util.is_timedelta64_object(val):
  144. return get_timedelta64_value(val) == NPY_NAT
  145. elif util.is_datetime64_object(val):
  146. return get_datetime64_value(val) == NPY_NAT
  147. else:
  148. return is_decimal_na(val)
  149. cdef bint is_decimal_na(object val):
  150. """
  151. Is this a decimal.Decimal object Decimal("NAN").
  152. """
  153. return isinstance(val, cDecimal) and val != val
  154. @cython.wraparound(False)
  155. @cython.boundscheck(False)
  156. cpdef ndarray[uint8_t] isnaobj(ndarray arr, bint inf_as_na=False):
  157. """
  158. Return boolean mask denoting which elements of a 1-D array are na-like,
  159. according to the criteria defined in `checknull`:
  160. - None
  161. - nan
  162. - NaT
  163. - np.datetime64 representation of NaT
  164. - np.timedelta64 representation of NaT
  165. - NA
  166. - Decimal("NaN")
  167. Parameters
  168. ----------
  169. arr : ndarray
  170. Returns
  171. -------
  172. result : ndarray (dtype=np.bool_)
  173. """
  174. cdef:
  175. Py_ssize_t i, n = arr.size
  176. object val
  177. bint is_null
  178. ndarray result = np.empty((<object>arr).shape, dtype=np.uint8)
  179. flatiter it = cnp.PyArray_IterNew(arr)
  180. flatiter it2 = cnp.PyArray_IterNew(result)
  181. for i in range(n):
  182. # The PyArray_GETITEM and PyArray_ITER_NEXT are faster
  183. # equivalents to `val = values[i]`
  184. val = cnp.PyArray_GETITEM(arr, cnp.PyArray_ITER_DATA(it))
  185. cnp.PyArray_ITER_NEXT(it)
  186. is_null = checknull(val, inf_as_na=inf_as_na)
  187. # Dereference pointer (set value)
  188. (<uint8_t *>(cnp.PyArray_ITER_DATA(it2)))[0] = <uint8_t>is_null
  189. cnp.PyArray_ITER_NEXT(it2)
  190. return result.view(np.bool_)
  191. def isposinf_scalar(val: object) -> bool:
  192. return util.is_float_object(val) and val == INF
  193. def isneginf_scalar(val: object) -> bool:
  194. return util.is_float_object(val) and val == NEGINF
  195. cdef bint is_null_datetime64(v):
  196. # determine if we have a null for a datetime (or integer versions),
  197. # excluding np.timedelta64('nat')
  198. if checknull_with_nat(v) or is_dt64nat(v):
  199. return True
  200. return False
  201. cdef bint is_null_timedelta64(v):
  202. # determine if we have a null for a timedelta (or integer versions),
  203. # excluding np.datetime64('nat')
  204. if checknull_with_nat(v) or is_td64nat(v):
  205. return True
  206. return False
  207. cdef bint checknull_with_nat_and_na(object obj):
  208. # See GH#32214
  209. return checknull_with_nat(obj) or obj is C_NA
  210. @cython.wraparound(False)
  211. @cython.boundscheck(False)
  212. def is_float_nan(values: ndarray) -> ndarray:
  213. """
  214. True for elements which correspond to a float nan
  215. Returns
  216. -------
  217. ndarray[bool]
  218. """
  219. cdef:
  220. ndarray[uint8_t] result
  221. Py_ssize_t i, N
  222. object val
  223. N = len(values)
  224. result = np.zeros(N, dtype=np.uint8)
  225. for i in range(N):
  226. val = values[i]
  227. if util.is_nan(val):
  228. result[i] = True
  229. return result.view(bool)
  230. @cython.wraparound(False)
  231. @cython.boundscheck(False)
  232. def is_numeric_na(values: ndarray) -> ndarray:
  233. """
  234. Check for NA values consistent with IntegerArray/FloatingArray.
  235. Similar to a vectorized is_valid_na_for_dtype restricted to numeric dtypes.
  236. Returns
  237. -------
  238. ndarray[bool]
  239. """
  240. cdef:
  241. ndarray[uint8_t] result
  242. Py_ssize_t i, N
  243. object val
  244. N = len(values)
  245. result = np.zeros(N, dtype=np.uint8)
  246. for i in range(N):
  247. val = values[i]
  248. if checknull(val):
  249. if val is None or val is C_NA or util.is_nan(val) or is_decimal_na(val):
  250. result[i] = True
  251. else:
  252. raise TypeError(f"'values' contains non-numeric NA {val}")
  253. return result.view(bool)
  254. # -----------------------------------------------------------------------------
  255. # Implementation of NA singleton
  256. def _create_binary_propagating_op(name, is_divmod=False):
  257. is_cmp = name.strip("_") in ["eq", "ne", "le", "lt", "ge", "gt"]
  258. def method(self, other):
  259. if (other is C_NA or isinstance(other, (str, bytes))
  260. or isinstance(other, (numbers.Number, np.bool_))
  261. or util.is_array(other) and not other.shape):
  262. # Need the other.shape clause to handle NumPy scalars,
  263. # since we do a setitem on `out` below, which
  264. # won't work for NumPy scalars.
  265. if is_divmod:
  266. return NA, NA
  267. else:
  268. return NA
  269. elif util.is_array(other):
  270. out = np.empty(other.shape, dtype=object)
  271. out[:] = NA
  272. if is_divmod:
  273. return out, out.copy()
  274. else:
  275. return out
  276. elif is_cmp and isinstance(other, (date, time, timedelta)):
  277. return NA
  278. return NotImplemented
  279. method.__name__ = name
  280. return method
  281. def _create_unary_propagating_op(name: str):
  282. def method(self):
  283. return NA
  284. method.__name__ = name
  285. return method
  286. cdef class C_NAType:
  287. pass
  288. class NAType(C_NAType):
  289. """
  290. NA ("not available") missing value indicator.
  291. .. warning::
  292. Experimental: the behaviour of NA can still change without warning.
  293. The NA singleton is a missing value indicator defined by pandas. It is
  294. used in certain new extension dtypes (currently the "string" dtype).
  295. """
  296. _instance = None
  297. def __new__(cls, *args, **kwargs):
  298. if NAType._instance is None:
  299. NAType._instance = C_NAType.__new__(cls, *args, **kwargs)
  300. return NAType._instance
  301. def __repr__(self) -> str:
  302. return "<NA>"
  303. def __format__(self, format_spec) -> str:
  304. try:
  305. return self.__repr__().__format__(format_spec)
  306. except ValueError:
  307. return self.__repr__()
  308. def __bool__(self):
  309. raise TypeError("boolean value of NA is ambiguous")
  310. def __hash__(self):
  311. # GH 30013: Ensure hash is large enough to avoid hash collisions with integers
  312. exponent = 31 if is_32bit else 61
  313. return 2 ** exponent - 1
  314. def __reduce__(self):
  315. return "NA"
  316. # Binary arithmetic and comparison ops -> propagate
  317. __add__ = _create_binary_propagating_op("__add__")
  318. __radd__ = _create_binary_propagating_op("__radd__")
  319. __sub__ = _create_binary_propagating_op("__sub__")
  320. __rsub__ = _create_binary_propagating_op("__rsub__")
  321. __mul__ = _create_binary_propagating_op("__mul__")
  322. __rmul__ = _create_binary_propagating_op("__rmul__")
  323. __matmul__ = _create_binary_propagating_op("__matmul__")
  324. __rmatmul__ = _create_binary_propagating_op("__rmatmul__")
  325. __truediv__ = _create_binary_propagating_op("__truediv__")
  326. __rtruediv__ = _create_binary_propagating_op("__rtruediv__")
  327. __floordiv__ = _create_binary_propagating_op("__floordiv__")
  328. __rfloordiv__ = _create_binary_propagating_op("__rfloordiv__")
  329. __mod__ = _create_binary_propagating_op("__mod__")
  330. __rmod__ = _create_binary_propagating_op("__rmod__")
  331. __divmod__ = _create_binary_propagating_op("__divmod__", is_divmod=True)
  332. __rdivmod__ = _create_binary_propagating_op("__rdivmod__", is_divmod=True)
  333. # __lshift__ and __rshift__ are not implemented
  334. __eq__ = _create_binary_propagating_op("__eq__")
  335. __ne__ = _create_binary_propagating_op("__ne__")
  336. __le__ = _create_binary_propagating_op("__le__")
  337. __lt__ = _create_binary_propagating_op("__lt__")
  338. __gt__ = _create_binary_propagating_op("__gt__")
  339. __ge__ = _create_binary_propagating_op("__ge__")
  340. # Unary ops
  341. __neg__ = _create_unary_propagating_op("__neg__")
  342. __pos__ = _create_unary_propagating_op("__pos__")
  343. __abs__ = _create_unary_propagating_op("__abs__")
  344. __invert__ = _create_unary_propagating_op("__invert__")
  345. # pow has special
  346. def __pow__(self, other):
  347. if other is C_NA:
  348. return NA
  349. elif isinstance(other, (numbers.Number, np.bool_)):
  350. if other == 0:
  351. # returning positive is correct for +/- 0.
  352. return type(other)(1)
  353. else:
  354. return NA
  355. elif util.is_array(other):
  356. return np.where(other == 0, other.dtype.type(1), NA)
  357. return NotImplemented
  358. def __rpow__(self, other):
  359. if other is C_NA:
  360. return NA
  361. elif isinstance(other, (numbers.Number, np.bool_)):
  362. if other == 1:
  363. return other
  364. else:
  365. return NA
  366. elif util.is_array(other):
  367. return np.where(other == 1, other, NA)
  368. return NotImplemented
  369. # Logical ops using Kleene logic
  370. def __and__(self, other):
  371. if other is False:
  372. return False
  373. elif other is True or other is C_NA:
  374. return NA
  375. return NotImplemented
  376. __rand__ = __and__
  377. def __or__(self, other):
  378. if other is True:
  379. return True
  380. elif other is False or other is C_NA:
  381. return NA
  382. return NotImplemented
  383. __ror__ = __or__
  384. def __xor__(self, other):
  385. if other is False or other is True or other is C_NA:
  386. return NA
  387. return NotImplemented
  388. __rxor__ = __xor__
  389. __array_priority__ = 1000
  390. _HANDLED_TYPES = (np.ndarray, numbers.Number, str, np.bool_)
  391. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  392. types = self._HANDLED_TYPES + (NAType,)
  393. for x in inputs:
  394. if not isinstance(x, types):
  395. return NotImplemented
  396. if method != "__call__":
  397. raise ValueError(f"ufunc method '{method}' not supported for NA")
  398. result = maybe_dispatch_ufunc_to_dunder_op(
  399. self, ufunc, method, *inputs, **kwargs
  400. )
  401. if result is NotImplemented:
  402. # For a NumPy ufunc that's not a binop, like np.logaddexp
  403. index = [i for i, x in enumerate(inputs) if x is NA][0]
  404. result = np.broadcast_arrays(*inputs)[index]
  405. if result.ndim == 0:
  406. result = result.item()
  407. if ufunc.nout > 1:
  408. result = (NA,) * ufunc.nout
  409. return result
  410. C_NA = NAType() # C-visible
  411. NA = C_NA # Python-visible