common.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. """
  2. Misc tools for implementing data structures
  3. Note: pandas.core.common is *not* part of the public API.
  4. """
  5. import collections
  6. from collections import abc
  7. from datetime import datetime, timedelta
  8. from functools import partial
  9. import inspect
  10. from typing import Any, Collection, Iterable, Union
  11. import numpy as np
  12. from pandas._libs import lib, tslibs
  13. from pandas._typing import T
  14. from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
  15. from pandas.core.dtypes.common import (
  16. is_array_like,
  17. is_bool_dtype,
  18. is_extension_array_dtype,
  19. is_integer,
  20. )
  21. from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries
  22. from pandas.core.dtypes.inference import _iterable_not_string
  23. from pandas.core.dtypes.missing import isna, isnull, notnull # noqa
  24. class SettingWithCopyError(ValueError):
  25. pass
  26. class SettingWithCopyWarning(Warning):
  27. pass
  28. def flatten(l):
  29. """
  30. Flatten an arbitrarily nested sequence.
  31. Parameters
  32. ----------
  33. l : sequence
  34. The non string sequence to flatten
  35. Notes
  36. -----
  37. This doesn't consider strings sequences.
  38. Returns
  39. -------
  40. flattened : generator
  41. """
  42. for el in l:
  43. if _iterable_not_string(el):
  44. for s in flatten(el):
  45. yield s
  46. else:
  47. yield el
  48. def consensus_name_attr(objs):
  49. name = objs[0].name
  50. for obj in objs[1:]:
  51. try:
  52. if obj.name != name:
  53. name = None
  54. except ValueError:
  55. name = None
  56. return name
  57. def maybe_box(indexer, values, obj, key):
  58. # if we have multiples coming back, box em
  59. if isinstance(values, np.ndarray):
  60. return obj[indexer.get_loc(key)]
  61. # return the value
  62. return values
  63. def maybe_box_datetimelike(value):
  64. # turn a datetime like into a Timestamp/timedelta as needed
  65. if isinstance(value, (np.datetime64, datetime)):
  66. value = tslibs.Timestamp(value)
  67. elif isinstance(value, (np.timedelta64, timedelta)):
  68. value = tslibs.Timedelta(value)
  69. return value
  70. values_from_object = lib.values_from_object
  71. def is_bool_indexer(key: Any) -> bool:
  72. """
  73. Check whether `key` is a valid boolean indexer.
  74. Parameters
  75. ----------
  76. key : Any
  77. Only list-likes may be considered boolean indexers.
  78. All other types are not considered a boolean indexer.
  79. For array-like input, boolean ndarrays or ExtensionArrays
  80. with ``_is_boolean`` set are considered boolean indexers.
  81. Returns
  82. -------
  83. bool
  84. Whether `key` is a valid boolean indexer.
  85. Raises
  86. ------
  87. ValueError
  88. When the array is an object-dtype ndarray or ExtensionArray
  89. and contains missing values.
  90. See Also
  91. --------
  92. check_array_indexer : Check that `key` is a valid array to index,
  93. and convert to an ndarray.
  94. """
  95. if isinstance(key, (ABCSeries, np.ndarray, ABCIndex)) or (
  96. is_array_like(key) and is_extension_array_dtype(key.dtype)
  97. ):
  98. if key.dtype == np.object_:
  99. key = np.asarray(values_from_object(key))
  100. if not lib.is_bool_array(key):
  101. na_msg = "Cannot mask with non-boolean array containing NA / NaN values"
  102. if isna(key).any():
  103. raise ValueError(na_msg)
  104. return False
  105. return True
  106. elif is_bool_dtype(key.dtype):
  107. return True
  108. elif isinstance(key, list):
  109. try:
  110. arr = np.asarray(key)
  111. return arr.dtype == np.bool_ and len(arr) == len(key)
  112. except TypeError: # pragma: no cover
  113. return False
  114. return False
  115. def cast_scalar_indexer(val):
  116. """
  117. To avoid numpy DeprecationWarnings, cast float to integer where valid.
  118. Parameters
  119. ----------
  120. val : scalar
  121. Returns
  122. -------
  123. outval : scalar
  124. """
  125. # assumes lib.is_scalar(val)
  126. if lib.is_float(val) and val == int(val):
  127. return int(val)
  128. return val
  129. def not_none(*args):
  130. """
  131. Returns a generator consisting of the arguments that are not None.
  132. """
  133. return (arg for arg in args if arg is not None)
  134. def any_none(*args):
  135. """
  136. Returns a boolean indicating if any argument is None.
  137. """
  138. return any(arg is None for arg in args)
  139. def all_none(*args):
  140. """
  141. Returns a boolean indicating if all arguments are None.
  142. """
  143. return all(arg is None for arg in args)
  144. def any_not_none(*args):
  145. """
  146. Returns a boolean indicating if any argument is not None.
  147. """
  148. return any(arg is not None for arg in args)
  149. def all_not_none(*args):
  150. """
  151. Returns a boolean indicating if all arguments are not None.
  152. """
  153. return all(arg is not None for arg in args)
  154. def count_not_none(*args):
  155. """
  156. Returns the count of arguments that are not None.
  157. """
  158. return sum(x is not None for x in args)
  159. def try_sort(iterable):
  160. listed = list(iterable)
  161. try:
  162. return sorted(listed)
  163. except TypeError:
  164. return listed
  165. def asarray_tuplesafe(values, dtype=None):
  166. if not (isinstance(values, (list, tuple)) or hasattr(values, "__array__")):
  167. values = list(values)
  168. elif isinstance(values, ABCIndexClass):
  169. return values.values
  170. if isinstance(values, list) and dtype in [np.object_, object]:
  171. return construct_1d_object_array_from_listlike(values)
  172. result = np.asarray(values, dtype=dtype)
  173. if issubclass(result.dtype.type, str):
  174. result = np.asarray(values, dtype=object)
  175. if result.ndim == 2:
  176. # Avoid building an array of arrays:
  177. values = [tuple(x) for x in values]
  178. result = construct_1d_object_array_from_listlike(values)
  179. return result
  180. def index_labels_to_array(labels, dtype=None):
  181. """
  182. Transform label or iterable of labels to array, for use in Index.
  183. Parameters
  184. ----------
  185. dtype : dtype
  186. If specified, use as dtype of the resulting array, otherwise infer.
  187. Returns
  188. -------
  189. array
  190. """
  191. if isinstance(labels, (str, tuple)):
  192. labels = [labels]
  193. if not isinstance(labels, (list, np.ndarray)):
  194. try:
  195. labels = list(labels)
  196. except TypeError: # non-iterable
  197. labels = [labels]
  198. labels = asarray_tuplesafe(labels, dtype=dtype)
  199. return labels
  200. def maybe_make_list(obj):
  201. if obj is not None and not isinstance(obj, (tuple, list)):
  202. return [obj]
  203. return obj
  204. def maybe_iterable_to_list(obj: Union[Iterable[T], T]) -> Union[Collection[T], T]:
  205. """
  206. If obj is Iterable but not list-like, consume into list.
  207. """
  208. if isinstance(obj, abc.Iterable) and not isinstance(obj, abc.Sized):
  209. return list(obj)
  210. return obj
  211. def is_null_slice(obj):
  212. """
  213. We have a null slice.
  214. """
  215. return (
  216. isinstance(obj, slice)
  217. and obj.start is None
  218. and obj.stop is None
  219. and obj.step is None
  220. )
  221. def is_true_slices(l):
  222. """
  223. Find non-trivial slices in "l": return a list of booleans with same length.
  224. """
  225. return [isinstance(k, slice) and not is_null_slice(k) for k in l]
  226. # TODO: used only once in indexing; belongs elsewhere?
  227. def is_full_slice(obj, l):
  228. """
  229. We have a full length slice.
  230. """
  231. return (
  232. isinstance(obj, slice) and obj.start == 0 and obj.stop == l and obj.step is None
  233. )
  234. def get_callable_name(obj):
  235. # typical case has name
  236. if hasattr(obj, "__name__"):
  237. return getattr(obj, "__name__")
  238. # some objects don't; could recurse
  239. if isinstance(obj, partial):
  240. return get_callable_name(obj.func)
  241. # fall back to class name
  242. if hasattr(obj, "__call__"):
  243. return type(obj).__name__
  244. # everything failed (probably because the argument
  245. # wasn't actually callable); we return None
  246. # instead of the empty string in this case to allow
  247. # distinguishing between no name and a name of ''
  248. return None
  249. def apply_if_callable(maybe_callable, obj, **kwargs):
  250. """
  251. Evaluate possibly callable input using obj and kwargs if it is callable,
  252. otherwise return as it is.
  253. Parameters
  254. ----------
  255. maybe_callable : possibly a callable
  256. obj : NDFrame
  257. **kwargs
  258. """
  259. if callable(maybe_callable):
  260. return maybe_callable(obj, **kwargs)
  261. return maybe_callable
  262. def dict_compat(d):
  263. """
  264. Helper function to convert datetimelike-keyed dicts
  265. to Timestamp-keyed dict.
  266. Parameters
  267. ----------
  268. d: dict like object
  269. Returns
  270. -------
  271. dict
  272. """
  273. return {maybe_box_datetimelike(key): value for key, value in d.items()}
  274. def standardize_mapping(into):
  275. """
  276. Helper function to standardize a supplied mapping.
  277. .. versionadded:: 0.21.0
  278. Parameters
  279. ----------
  280. into : instance or subclass of collections.abc.Mapping
  281. Must be a class, an initialized collections.defaultdict,
  282. or an instance of a collections.abc.Mapping subclass.
  283. Returns
  284. -------
  285. mapping : a collections.abc.Mapping subclass or other constructor
  286. a callable object that can accept an iterator to create
  287. the desired Mapping.
  288. See Also
  289. --------
  290. DataFrame.to_dict
  291. Series.to_dict
  292. """
  293. if not inspect.isclass(into):
  294. if isinstance(into, collections.defaultdict):
  295. return partial(collections.defaultdict, into.default_factory)
  296. into = type(into)
  297. if not issubclass(into, abc.Mapping):
  298. raise TypeError(f"unsupported type: {into}")
  299. elif into == collections.defaultdict:
  300. raise TypeError("to_dict() only accepts initialized defaultdicts")
  301. return into
  302. def random_state(state=None):
  303. """
  304. Helper function for processing random_state arguments.
  305. Parameters
  306. ----------
  307. state : int, np.random.RandomState, None.
  308. If receives an int, passes to np.random.RandomState() as seed.
  309. If receives an np.random.RandomState object, just returns object.
  310. If receives `None`, returns np.random.
  311. If receives anything else, raises an informative ValueError.
  312. Default None.
  313. Returns
  314. -------
  315. np.random.RandomState
  316. """
  317. if is_integer(state):
  318. return np.random.RandomState(state)
  319. elif isinstance(state, np.random.RandomState):
  320. return state
  321. elif state is None:
  322. return np.random
  323. else:
  324. raise ValueError(
  325. "random_state must be an integer, a numpy RandomState, or None"
  326. )
  327. def pipe(obj, func, *args, **kwargs):
  328. """
  329. Apply a function ``func`` to object ``obj`` either by passing obj as the
  330. first argument to the function or, in the case that the func is a tuple,
  331. interpret the first element of the tuple as a function and pass the obj to
  332. that function as a keyword argument whose key is the value of the second
  333. element of the tuple.
  334. Parameters
  335. ----------
  336. func : callable or tuple of (callable, str)
  337. Function to apply to this object or, alternatively, a
  338. ``(callable, data_keyword)`` tuple where ``data_keyword`` is a
  339. string indicating the keyword of `callable`` that expects the
  340. object.
  341. *args : iterable, optional
  342. Positional arguments passed into ``func``.
  343. **kwargs : dict, optional
  344. A dictionary of keyword arguments passed into ``func``.
  345. Returns
  346. -------
  347. object : the return type of ``func``.
  348. """
  349. if isinstance(func, tuple):
  350. func, target = func
  351. if target in kwargs:
  352. msg = f"{target} is both the pipe target and a keyword argument"
  353. raise ValueError(msg)
  354. kwargs[target] = obj
  355. return func(*args, **kwargs)
  356. else:
  357. return func(obj, *args, **kwargs)
  358. def get_rename_function(mapper):
  359. """
  360. Returns a function that will map names/labels, dependent if mapper
  361. is a dict, Series or just a function.
  362. """
  363. if isinstance(mapper, (abc.Mapping, ABCSeries)):
  364. def f(x):
  365. if x in mapper:
  366. return mapper[x]
  367. else:
  368. return x
  369. else:
  370. f = mapper
  371. return f