__init__.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. """
  2. Expose public exceptions & warnings
  3. """
  4. from __future__ import annotations
  5. import ctypes
  6. from pandas._config.config import OptionError
  7. from pandas._libs.tslibs import (
  8. OutOfBoundsDatetime,
  9. OutOfBoundsTimedelta,
  10. )
  11. from pandas.util.version import InvalidVersion
  12. class IntCastingNaNError(ValueError):
  13. """
  14. Exception raised when converting (``astype``) an array with NaN to an integer type.
  15. Examples
  16. --------
  17. >>> pd.DataFrame(np.array([[1, np.nan], [2, 3]]), dtype="i8")
  18. Traceback (most recent call last):
  19. IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer
  20. """
  21. class NullFrequencyError(ValueError):
  22. """
  23. Exception raised when a ``freq`` cannot be null.
  24. Particularly ``DatetimeIndex.shift``, ``TimedeltaIndex.shift``,
  25. ``PeriodIndex.shift``.
  26. Examples
  27. --------
  28. >>> df = pd.DatetimeIndex(["2011-01-01 10:00", "2011-01-01"], freq=None)
  29. >>> df.shift(2)
  30. Traceback (most recent call last):
  31. NullFrequencyError: Cannot shift with no freq
  32. """
  33. class PerformanceWarning(Warning):
  34. """
  35. Warning raised when there is a possible performance impact.
  36. Examples
  37. --------
  38. >>> df = pd.DataFrame({"jim": [0, 0, 1, 1],
  39. ... "joe": ["x", "x", "z", "y"],
  40. ... "jolie": [1, 2, 3, 4]})
  41. >>> df = df.set_index(["jim", "joe"])
  42. >>> df
  43. jolie
  44. jim joe
  45. 0 x 1
  46. x 2
  47. 1 z 3
  48. y 4
  49. >>> df.loc[(1, 'z')] # doctest: +SKIP
  50. # PerformanceWarning: indexing past lexsort depth may impact performance.
  51. df.loc[(1, 'z')]
  52. jolie
  53. jim joe
  54. 1 z 3
  55. """
  56. class UnsupportedFunctionCall(ValueError):
  57. """
  58. Exception raised when attempting to call a unsupported numpy function.
  59. For example, ``np.cumsum(groupby_object)``.
  60. Examples
  61. --------
  62. >>> df = pd.DataFrame({"A": [0, 0, 1, 1],
  63. ... "B": ["x", "x", "z", "y"],
  64. ... "C": [1, 2, 3, 4]}
  65. ... )
  66. >>> np.cumsum(df.groupby(["A"]))
  67. Traceback (most recent call last):
  68. UnsupportedFunctionCall: numpy operations are not valid with groupby.
  69. Use .groupby(...).cumsum() instead
  70. """
  71. class UnsortedIndexError(KeyError):
  72. """
  73. Error raised when slicing a MultiIndex which has not been lexsorted.
  74. Subclass of `KeyError`.
  75. Examples
  76. --------
  77. >>> df = pd.DataFrame({"cat": [0, 0, 1, 1],
  78. ... "color": ["white", "white", "brown", "black"],
  79. ... "lives": [4, 4, 3, 7]},
  80. ... )
  81. >>> df = df.set_index(["cat", "color"])
  82. >>> df
  83. lives
  84. cat color
  85. 0 white 4
  86. white 4
  87. 1 brown 3
  88. black 7
  89. >>> df.loc[(0, "black"):(1, "white")]
  90. Traceback (most recent call last):
  91. UnsortedIndexError: 'Key length (2) was greater
  92. than MultiIndex lexsort depth (1)'
  93. """
  94. class ParserError(ValueError):
  95. """
  96. Exception that is raised by an error encountered in parsing file contents.
  97. This is a generic error raised for errors encountered when functions like
  98. `read_csv` or `read_html` are parsing contents of a file.
  99. See Also
  100. --------
  101. read_csv : Read CSV (comma-separated) file into a DataFrame.
  102. read_html : Read HTML table into a DataFrame.
  103. Examples
  104. --------
  105. >>> data = '''a,b,c
  106. ... cat,foo,bar
  107. ... dog,foo,"baz'''
  108. >>> from io import StringIO
  109. >>> pd.read_csv(StringIO(data), skipfooter=1, engine='python')
  110. Traceback (most recent call last):
  111. ParserError: ',' expected after '"'. Error could possibly be due
  112. to parsing errors in the skipped footer rows
  113. """
  114. class DtypeWarning(Warning):
  115. """
  116. Warning raised when reading different dtypes in a column from a file.
  117. Raised for a dtype incompatibility. This can happen whenever `read_csv`
  118. or `read_table` encounter non-uniform dtypes in a column(s) of a given
  119. CSV file.
  120. See Also
  121. --------
  122. read_csv : Read CSV (comma-separated) file into a DataFrame.
  123. read_table : Read general delimited file into a DataFrame.
  124. Notes
  125. -----
  126. This warning is issued when dealing with larger files because the dtype
  127. checking happens per chunk read.
  128. Despite the warning, the CSV file is read with mixed types in a single
  129. column which will be an object type. See the examples below to better
  130. understand this issue.
  131. Examples
  132. --------
  133. This example creates and reads a large CSV file with a column that contains
  134. `int` and `str`.
  135. >>> df = pd.DataFrame({'a': (['1'] * 100000 + ['X'] * 100000 +
  136. ... ['1'] * 100000),
  137. ... 'b': ['b'] * 300000}) # doctest: +SKIP
  138. >>> df.to_csv('test.csv', index=False) # doctest: +SKIP
  139. >>> df2 = pd.read_csv('test.csv') # doctest: +SKIP
  140. ... # DtypeWarning: Columns (0) have mixed types
  141. Important to notice that ``df2`` will contain both `str` and `int` for the
  142. same input, '1'.
  143. >>> df2.iloc[262140, 0] # doctest: +SKIP
  144. '1'
  145. >>> type(df2.iloc[262140, 0]) # doctest: +SKIP
  146. <class 'str'>
  147. >>> df2.iloc[262150, 0] # doctest: +SKIP
  148. 1
  149. >>> type(df2.iloc[262150, 0]) # doctest: +SKIP
  150. <class 'int'>
  151. One way to solve this issue is using the `dtype` parameter in the
  152. `read_csv` and `read_table` functions to explicit the conversion:
  153. >>> df2 = pd.read_csv('test.csv', sep=',', dtype={'a': str}) # doctest: +SKIP
  154. No warning was issued.
  155. """
  156. class EmptyDataError(ValueError):
  157. """
  158. Exception raised in ``pd.read_csv`` when empty data or header is encountered.
  159. Examples
  160. --------
  161. >>> from io import StringIO
  162. >>> empty = StringIO()
  163. >>> pd.read_csv(empty)
  164. Traceback (most recent call last):
  165. EmptyDataError: No columns to parse from file
  166. """
  167. class ParserWarning(Warning):
  168. """
  169. Warning raised when reading a file that doesn't use the default 'c' parser.
  170. Raised by `pd.read_csv` and `pd.read_table` when it is necessary to change
  171. parsers, generally from the default 'c' parser to 'python'.
  172. It happens due to a lack of support or functionality for parsing a
  173. particular attribute of a CSV file with the requested engine.
  174. Currently, 'c' unsupported options include the following parameters:
  175. 1. `sep` other than a single character (e.g. regex separators)
  176. 2. `skipfooter` higher than 0
  177. 3. `sep=None` with `delim_whitespace=False`
  178. The warning can be avoided by adding `engine='python'` as a parameter in
  179. `pd.read_csv` and `pd.read_table` methods.
  180. See Also
  181. --------
  182. pd.read_csv : Read CSV (comma-separated) file into DataFrame.
  183. pd.read_table : Read general delimited file into DataFrame.
  184. Examples
  185. --------
  186. Using a `sep` in `pd.read_csv` other than a single character:
  187. >>> import io
  188. >>> csv = '''a;b;c
  189. ... 1;1,8
  190. ... 1;2,1'''
  191. >>> df = pd.read_csv(io.StringIO(csv), sep='[;,]') # doctest: +SKIP
  192. ... # ParserWarning: Falling back to the 'python' engine...
  193. Adding `engine='python'` to `pd.read_csv` removes the Warning:
  194. >>> df = pd.read_csv(io.StringIO(csv), sep='[;,]', engine='python')
  195. """
  196. class MergeError(ValueError):
  197. """
  198. Exception raised when merging data.
  199. Subclass of ``ValueError``.
  200. Examples
  201. --------
  202. >>> left = pd.DataFrame({"a": ["a", "b", "b", "d"],
  203. ... "b": ["cat", "dog", "weasel", "horse"]},
  204. ... index=range(4))
  205. >>> right = pd.DataFrame({"a": ["a", "b", "c", "d"],
  206. ... "c": ["meow", "bark", "chirp", "nay"]},
  207. ... index=range(4)).set_index("a")
  208. >>> left.join(right, on="a", validate="one_to_one",)
  209. Traceback (most recent call last):
  210. MergeError: Merge keys are not unique in left dataset; not a one-to-one merge
  211. """
  212. class AbstractMethodError(NotImplementedError):
  213. """
  214. Raise this error instead of NotImplementedError for abstract methods.
  215. Examples
  216. --------
  217. >>> class Foo:
  218. ... @classmethod
  219. ... def classmethod(cls):
  220. ... raise pd.errors.AbstractMethodError(cls, methodtype="classmethod")
  221. ... def method(self):
  222. ... raise pd.errors.AbstractMethodError(self)
  223. >>> test = Foo.classmethod()
  224. Traceback (most recent call last):
  225. AbstractMethodError: This classmethod must be defined in the concrete class Foo
  226. >>> test2 = Foo().method()
  227. Traceback (most recent call last):
  228. AbstractMethodError: This classmethod must be defined in the concrete class Foo
  229. """
  230. def __init__(self, class_instance, methodtype: str = "method") -> None:
  231. types = {"method", "classmethod", "staticmethod", "property"}
  232. if methodtype not in types:
  233. raise ValueError(
  234. f"methodtype must be one of {methodtype}, got {types} instead."
  235. )
  236. self.methodtype = methodtype
  237. self.class_instance = class_instance
  238. def __str__(self) -> str:
  239. if self.methodtype == "classmethod":
  240. name = self.class_instance.__name__
  241. else:
  242. name = type(self.class_instance).__name__
  243. return f"This {self.methodtype} must be defined in the concrete class {name}"
  244. class NumbaUtilError(Exception):
  245. """
  246. Error raised for unsupported Numba engine routines.
  247. Examples
  248. --------
  249. >>> df = pd.DataFrame({"key": ["a", "a", "b", "b"], "data": [1, 2, 3, 4]},
  250. ... columns=["key", "data"])
  251. >>> def incorrect_function(x):
  252. ... return sum(x) * 2.7
  253. >>> df.groupby("key").agg(incorrect_function, engine="numba")
  254. Traceback (most recent call last):
  255. NumbaUtilError: The first 2 arguments to incorrect_function
  256. must be ['values', 'index']
  257. """
  258. class DuplicateLabelError(ValueError):
  259. """
  260. Error raised when an operation would introduce duplicate labels.
  261. Examples
  262. --------
  263. >>> s = pd.Series([0, 1, 2], index=['a', 'b', 'c']).set_flags(
  264. ... allows_duplicate_labels=False
  265. ... )
  266. >>> s.reindex(['a', 'a', 'b'])
  267. Traceback (most recent call last):
  268. ...
  269. DuplicateLabelError: Index has duplicates.
  270. positions
  271. label
  272. a [0, 1]
  273. """
  274. class InvalidIndexError(Exception):
  275. """
  276. Exception raised when attempting to use an invalid index key.
  277. Examples
  278. --------
  279. >>> idx = pd.MultiIndex.from_product([["x", "y"], [0, 1]])
  280. >>> df = pd.DataFrame([[1, 1, 2, 2],
  281. ... [3, 3, 4, 4]], columns=idx)
  282. >>> df
  283. x y
  284. 0 1 0 1
  285. 0 1 1 2 2
  286. 1 3 3 4 4
  287. >>> df[:, 0]
  288. Traceback (most recent call last):
  289. InvalidIndexError: (slice(None, None, None), 0)
  290. """
  291. class DataError(Exception):
  292. """
  293. Exceptionn raised when performing an operation on non-numerical data.
  294. For example, calling ``ohlc`` on a non-numerical column or a function
  295. on a rolling window.
  296. Examples
  297. --------
  298. >>> ser = pd.Series(['a', 'b', 'c'])
  299. >>> ser.rolling(2).sum()
  300. Traceback (most recent call last):
  301. DataError: No numeric types to aggregate
  302. """
  303. class SpecificationError(Exception):
  304. """
  305. Exception raised by ``agg`` when the functions are ill-specified.
  306. The exception raised in two scenarios.
  307. The first way is calling ``agg`` on a
  308. Dataframe or Series using a nested renamer (dict-of-dict).
  309. The second way is calling ``agg`` on a Dataframe with duplicated functions
  310. names without assigning column name.
  311. Examples
  312. --------
  313. >>> df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
  314. ... 'B': range(5),
  315. ... 'C': range(5)})
  316. >>> df.groupby('A').B.agg({'foo': 'count'}) # doctest: +SKIP
  317. ... # SpecificationError: nested renamer is not supported
  318. >>> df.groupby('A').agg({'B': {'foo': ['sum', 'max']}}) # doctest: +SKIP
  319. ... # SpecificationError: nested renamer is not supported
  320. >>> df.groupby('A').agg(['min', 'min']) # doctest: +SKIP
  321. ... # SpecificationError: nested renamer is not supported
  322. """
  323. class SettingWithCopyError(ValueError):
  324. """
  325. Exception raised when trying to set on a copied slice from a ``DataFrame``.
  326. The ``mode.chained_assignment`` needs to be set to set to 'raise.' This can
  327. happen unintentionally when chained indexing.
  328. For more information on evaluation order,
  329. see :ref:`the user guide<indexing.evaluation_order>`.
  330. For more information on view vs. copy,
  331. see :ref:`the user guide<indexing.view_versus_copy>`.
  332. Examples
  333. --------
  334. >>> pd.options.mode.chained_assignment = 'raise'
  335. >>> df = pd.DataFrame({'A': [1, 1, 1, 2, 2]}, columns=['A'])
  336. >>> df.loc[0:3]['A'] = 'a' # doctest: +SKIP
  337. ... # SettingWithCopyError: A value is trying to be set on a copy of a...
  338. """
  339. class SettingWithCopyWarning(Warning):
  340. """
  341. Warning raised when trying to set on a copied slice from a ``DataFrame``.
  342. The ``mode.chained_assignment`` needs to be set to set to 'warn.'
  343. 'Warn' is the default option. This can happen unintentionally when
  344. chained indexing.
  345. For more information on evaluation order,
  346. see :ref:`the user guide<indexing.evaluation_order>`.
  347. For more information on view vs. copy,
  348. see :ref:`the user guide<indexing.view_versus_copy>`.
  349. Examples
  350. --------
  351. >>> df = pd.DataFrame({'A': [1, 1, 1, 2, 2]}, columns=['A'])
  352. >>> df.loc[0:3]['A'] = 'a' # doctest: +SKIP
  353. ... # SettingWithCopyWarning: A value is trying to be set on a copy of a...
  354. """
  355. class ChainedAssignmentError(Warning):
  356. """
  357. Warning raised when trying to set using chained assignment.
  358. When the ``mode.copy_on_write`` option is enabled, chained assignment can
  359. never work. In such a situation, we are always setting into a temporary
  360. object that is the result of an indexing operation (getitem), which under
  361. Copy-on-Write always behaves as a copy. Thus, assigning through a chain
  362. can never update the original Series or DataFrame.
  363. For more information on view vs. copy,
  364. see :ref:`the user guide<indexing.view_versus_copy>`.
  365. Examples
  366. --------
  367. >>> pd.options.mode.copy_on_write = True
  368. >>> df = pd.DataFrame({'A': [1, 1, 1, 2, 2]}, columns=['A'])
  369. >>> df["A"][0:3] = 10 # doctest: +SKIP
  370. ... # ChainedAssignmentError: ...
  371. >>> pd.options.mode.copy_on_write = False
  372. """
  373. _chained_assignment_msg = (
  374. "A value is trying to be set on a copy of a DataFrame or Series "
  375. "through chained assignment.\n"
  376. "When using the Copy-on-Write mode, such chained assignment never works "
  377. "to update the original DataFrame or Series, because the intermediate "
  378. "object on which we are setting values always behaves as a copy.\n\n"
  379. "Try using '.loc[row_indexer, col_indexer] = value' instead, to perform "
  380. "the assignment in a single step.\n\n"
  381. "See the caveats in the documentation: "
  382. "https://pandas.pydata.org/pandas-docs/stable/user_guide/"
  383. "indexing.html#returning-a-view-versus-a-copy"
  384. )
  385. _chained_assignment_method_msg = (
  386. "A value is trying to be set on a copy of a DataFrame or Series "
  387. "through chained assignment using an inplace method.\n"
  388. "When using the Copy-on-Write mode, such inplace method never works "
  389. "to update the original DataFrame or Series, because the intermediate "
  390. "object on which we are setting values always behaves as a copy.\n\n"
  391. "For example, when doing 'df[col].method(value, inplace=True)', try "
  392. "using 'df.method({col: value}, inplace=True)' instead, to perform "
  393. "the operation inplace on the original object.\n\n"
  394. )
  395. _chained_assignment_warning_msg = (
  396. "ChainedAssignmentError: behaviour will change in pandas 3.0!\n"
  397. "You are setting values through chained assignment. Currently this works "
  398. "in certain cases, but when using Copy-on-Write (which will become the "
  399. "default behaviour in pandas 3.0) this will never work to update the "
  400. "original DataFrame or Series, because the intermediate object on which "
  401. "we are setting values will behave as a copy.\n"
  402. "A typical example is when you are setting values in a column of a "
  403. "DataFrame, like:\n\n"
  404. 'df["col"][row_indexer] = value\n\n'
  405. 'Use `df.loc[row_indexer, "col"] = values` instead, to perform the '
  406. "assignment in a single step and ensure this keeps updating the original `df`.\n\n"
  407. "See the caveats in the documentation: "
  408. "https://pandas.pydata.org/pandas-docs/stable/user_guide/"
  409. "indexing.html#returning-a-view-versus-a-copy\n"
  410. )
  411. _chained_assignment_warning_method_msg = (
  412. "A value is trying to be set on a copy of a DataFrame or Series "
  413. "through chained assignment using an inplace method.\n"
  414. "The behavior will change in pandas 3.0. This inplace method will "
  415. "never work because the intermediate object on which we are setting "
  416. "values always behaves as a copy.\n\n"
  417. "For example, when doing 'df[col].method(value, inplace=True)', try "
  418. "using 'df.method({col: value}, inplace=True)' or "
  419. "df[col] = df[col].method(value) instead, to perform "
  420. "the operation inplace on the original object.\n\n"
  421. )
  422. def _check_cacher(obj):
  423. # This is a mess, selection paths that return a view set the _cacher attribute
  424. # on the Series; most of them also set _item_cache which adds 1 to our relevant
  425. # reference count, but iloc does not, so we have to check if we are actually
  426. # in the item cache
  427. if hasattr(obj, "_cacher"):
  428. parent = obj._cacher[1]()
  429. # parent could be dead
  430. if parent is None:
  431. return False
  432. if hasattr(parent, "_item_cache"):
  433. if obj._cacher[0] in parent._item_cache:
  434. # Check if we are actually the item from item_cache, iloc creates a
  435. # new object
  436. return obj is parent._item_cache[obj._cacher[0]]
  437. return False
  438. class NumExprClobberingError(NameError):
  439. """
  440. Exception raised when trying to use a built-in numexpr name as a variable name.
  441. ``eval`` or ``query`` will throw the error if the engine is set
  442. to 'numexpr'. 'numexpr' is the default engine value for these methods if the
  443. numexpr package is installed.
  444. Examples
  445. --------
  446. >>> df = pd.DataFrame({'abs': [1, 1, 1]})
  447. >>> df.query("abs > 2") # doctest: +SKIP
  448. ... # NumExprClobberingError: Variables in expression "(abs) > (2)" overlap...
  449. >>> sin, a = 1, 2
  450. >>> pd.eval("sin + a", engine='numexpr') # doctest: +SKIP
  451. ... # NumExprClobberingError: Variables in expression "(sin) + (a)" overlap...
  452. """
  453. class UndefinedVariableError(NameError):
  454. """
  455. Exception raised by ``query`` or ``eval`` when using an undefined variable name.
  456. It will also specify whether the undefined variable is local or not.
  457. Examples
  458. --------
  459. >>> df = pd.DataFrame({'A': [1, 1, 1]})
  460. >>> df.query("A > x") # doctest: +SKIP
  461. ... # UndefinedVariableError: name 'x' is not defined
  462. >>> df.query("A > @y") # doctest: +SKIP
  463. ... # UndefinedVariableError: local variable 'y' is not defined
  464. >>> pd.eval('x + 1') # doctest: +SKIP
  465. ... # UndefinedVariableError: name 'x' is not defined
  466. """
  467. def __init__(self, name: str, is_local: bool | None = None) -> None:
  468. base_msg = f"{repr(name)} is not defined"
  469. if is_local:
  470. msg = f"local variable {base_msg}"
  471. else:
  472. msg = f"name {base_msg}"
  473. super().__init__(msg)
  474. class IndexingError(Exception):
  475. """
  476. Exception is raised when trying to index and there is a mismatch in dimensions.
  477. Examples
  478. --------
  479. >>> df = pd.DataFrame({'A': [1, 1, 1]})
  480. >>> df.loc[..., ..., 'A'] # doctest: +SKIP
  481. ... # IndexingError: indexer may only contain one '...' entry
  482. >>> df = pd.DataFrame({'A': [1, 1, 1]})
  483. >>> df.loc[1, ..., ...] # doctest: +SKIP
  484. ... # IndexingError: Too many indexers
  485. >>> df[pd.Series([True], dtype=bool)] # doctest: +SKIP
  486. ... # IndexingError: Unalignable boolean Series provided as indexer...
  487. >>> s = pd.Series(range(2),
  488. ... index = pd.MultiIndex.from_product([["a", "b"], ["c"]]))
  489. >>> s.loc["a", "c", "d"] # doctest: +SKIP
  490. ... # IndexingError: Too many indexers
  491. """
  492. class PyperclipException(RuntimeError):
  493. """
  494. Exception raised when clipboard functionality is unsupported.
  495. Raised by ``to_clipboard()`` and ``read_clipboard()``.
  496. """
  497. class PyperclipWindowsException(PyperclipException):
  498. """
  499. Exception raised when clipboard functionality is unsupported by Windows.
  500. Access to the clipboard handle would be denied due to some other
  501. window process is accessing it.
  502. """
  503. def __init__(self, message: str) -> None:
  504. # attr only exists on Windows, so typing fails on other platforms
  505. message += f" ({ctypes.WinError()})" # type: ignore[attr-defined]
  506. super().__init__(message)
  507. class CSSWarning(UserWarning):
  508. """
  509. Warning is raised when converting css styling fails.
  510. This can be due to the styling not having an equivalent value or because the
  511. styling isn't properly formatted.
  512. Examples
  513. --------
  514. >>> df = pd.DataFrame({'A': [1, 1, 1]})
  515. >>> df.style.applymap(
  516. ... lambda x: 'background-color: blueGreenRed;'
  517. ... ).to_excel('styled.xlsx') # doctest: +SKIP
  518. CSSWarning: Unhandled color format: 'blueGreenRed'
  519. >>> df.style.applymap(
  520. ... lambda x: 'border: 1px solid red red;'
  521. ... ).to_excel('styled.xlsx') # doctest: +SKIP
  522. CSSWarning: Unhandled color format: 'blueGreenRed'
  523. """
  524. class PossibleDataLossError(Exception):
  525. """
  526. Exception raised when trying to open a HDFStore file when already opened.
  527. Examples
  528. --------
  529. >>> store = pd.HDFStore('my-store', 'a') # doctest: +SKIP
  530. >>> store.open("w") # doctest: +SKIP
  531. ... # PossibleDataLossError: Re-opening the file [my-store] with mode [a]...
  532. """
  533. class ClosedFileError(Exception):
  534. """
  535. Exception is raised when trying to perform an operation on a closed HDFStore file.
  536. Examples
  537. --------
  538. >>> store = pd.HDFStore('my-store', 'a') # doctest: +SKIP
  539. >>> store.close() # doctest: +SKIP
  540. >>> store.keys() # doctest: +SKIP
  541. ... # ClosedFileError: my-store file is not open!
  542. """
  543. class IncompatibilityWarning(Warning):
  544. """
  545. Warning raised when trying to use where criteria on an incompatible HDF5 file.
  546. """
  547. class AttributeConflictWarning(Warning):
  548. """
  549. Warning raised when index attributes conflict when using HDFStore.
  550. Occurs when attempting to append an index with a different
  551. name than the existing index on an HDFStore or attempting to append an index with a
  552. different frequency than the existing index on an HDFStore.
  553. Examples
  554. --------
  555. >>> idx1 = pd.Index(['a', 'b'], name='name1')
  556. >>> df1 = pd.DataFrame([[1, 2], [3, 4]], index=idx1)
  557. >>> df1.to_hdf('file', 'data', 'w', append=True) # doctest: +SKIP
  558. >>> idx2 = pd.Index(['c', 'd'], name='name2')
  559. >>> df2 = pd.DataFrame([[5, 6], [7, 8]], index=idx2)
  560. >>> df2.to_hdf('file', 'data', 'a', append=True) # doctest: +SKIP
  561. AttributeConflictWarning: the [index_name] attribute of the existing index is
  562. [name1] which conflicts with the new [name2]...
  563. """
  564. class DatabaseError(OSError):
  565. """
  566. Error is raised when executing sql with bad syntax or sql that throws an error.
  567. Examples
  568. --------
  569. >>> from sqlite3 import connect
  570. >>> conn = connect(':memory:')
  571. >>> pd.read_sql('select * test', conn) # doctest: +SKIP
  572. ... # DatabaseError: Execution failed on sql 'test': near "test": syntax error
  573. """
  574. class PossiblePrecisionLoss(Warning):
  575. """
  576. Warning raised by to_stata on a column with a value outside or equal to int64.
  577. When the column value is outside or equal to the int64 value the column is
  578. converted to a float64 dtype.
  579. Examples
  580. --------
  581. >>> df = pd.DataFrame({"s": pd.Series([1, 2**53], dtype=np.int64)})
  582. >>> df.to_stata('test') # doctest: +SKIP
  583. ... # PossiblePrecisionLoss: Column converted from int64 to float64...
  584. """
  585. class ValueLabelTypeMismatch(Warning):
  586. """
  587. Warning raised by to_stata on a category column that contains non-string values.
  588. Examples
  589. --------
  590. >>> df = pd.DataFrame({"categories": pd.Series(["a", 2], dtype="category")})
  591. >>> df.to_stata('test') # doctest: +SKIP
  592. ... # ValueLabelTypeMismatch: Stata value labels (pandas categories) must be str...
  593. """
  594. class InvalidColumnName(Warning):
  595. """
  596. Warning raised by to_stata the column contains a non-valid stata name.
  597. Because the column name is an invalid Stata variable, the name needs to be
  598. converted.
  599. Examples
  600. --------
  601. >>> df = pd.DataFrame({"0categories": pd.Series([2, 2])})
  602. >>> df.to_stata('test') # doctest: +SKIP
  603. ... # InvalidColumnName: Not all pandas column names were valid Stata variable...
  604. """
  605. class CategoricalConversionWarning(Warning):
  606. """
  607. Warning is raised when reading a partial labeled Stata file using a iterator.
  608. Examples
  609. --------
  610. >>> from pandas.io.stata import StataReader
  611. >>> with StataReader('dta_file', chunksize=2) as reader: # doctest: +SKIP
  612. ... for i, block in enumerate(reader):
  613. ... print(i, block)
  614. ... # CategoricalConversionWarning: One or more series with value labels...
  615. """
  616. class LossySetitemError(Exception):
  617. """
  618. Raised when trying to do a __setitem__ on an np.ndarray that is not lossless.
  619. Notes
  620. -----
  621. This is an internal error.
  622. """
  623. class NoBufferPresent(Exception):
  624. """
  625. Exception is raised in _get_data_buffer to signal that there is no requested buffer.
  626. """
  627. class InvalidComparison(Exception):
  628. """
  629. Exception is raised by _validate_comparison_value to indicate an invalid comparison.
  630. Notes
  631. -----
  632. This is an internal error.
  633. """
  634. __all__ = [
  635. "AbstractMethodError",
  636. "AttributeConflictWarning",
  637. "CategoricalConversionWarning",
  638. "ClosedFileError",
  639. "CSSWarning",
  640. "DatabaseError",
  641. "DataError",
  642. "DtypeWarning",
  643. "DuplicateLabelError",
  644. "EmptyDataError",
  645. "IncompatibilityWarning",
  646. "IntCastingNaNError",
  647. "InvalidColumnName",
  648. "InvalidComparison",
  649. "InvalidIndexError",
  650. "InvalidVersion",
  651. "IndexingError",
  652. "LossySetitemError",
  653. "MergeError",
  654. "NoBufferPresent",
  655. "NullFrequencyError",
  656. "NumbaUtilError",
  657. "NumExprClobberingError",
  658. "OptionError",
  659. "OutOfBoundsDatetime",
  660. "OutOfBoundsTimedelta",
  661. "ParserError",
  662. "ParserWarning",
  663. "PerformanceWarning",
  664. "PossibleDataLossError",
  665. "PossiblePrecisionLoss",
  666. "PyperclipException",
  667. "PyperclipWindowsException",
  668. "SettingWithCopyError",
  669. "SettingWithCopyWarning",
  670. "SpecificationError",
  671. "UndefinedVariableError",
  672. "UnsortedIndexError",
  673. "UnsupportedFunctionCall",
  674. "ValueLabelTypeMismatch",
  675. ]