Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pandas/errors/__init__.py: 78%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

79 statements  

1""" 

2Expose public exceptions & warnings 

3""" 

4 

5from __future__ import annotations 

6 

7import abc 

8import ctypes 

9 

10from pandas._config.config import OptionError 

11 

12from pandas._libs.tslibs import ( 

13 IncompatibleFrequency, 

14 OutOfBoundsDatetime, 

15 OutOfBoundsTimedelta, 

16) 

17 

18from pandas.util.version import InvalidVersion 

19 

20 

21class IntCastingNaNError(ValueError): 

22 """ 

23 Exception raised when converting (``astype``) an array with NaN to an integer type. 

24 

25 This error occurs when attempting to cast a data structure containing non-finite 

26 values (such as NaN or infinity) to an integer data type. Integer types do not 

27 support non-finite values, so such conversions are explicitly disallowed to 

28 prevent silent data corruption or unexpected behavior. 

29 

30 See Also 

31 -------- 

32 DataFrame.astype : Method to cast a pandas DataFrame object to a specified dtype. 

33 Series.astype : Method to cast a pandas Series object to a specified dtype. 

34 

35 Examples 

36 -------- 

37 >>> pd.DataFrame(np.array([[1, np.nan], [2, 3]]), dtype="i8") 

38 Traceback (most recent call last): 

39 IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer 

40 """ 

41 

42 

43class NullFrequencyError(ValueError): 

44 """ 

45 Exception raised when a ``freq`` cannot be null. 

46 

47 Particularly ``DatetimeIndex.shift``, ``TimedeltaIndex.shift``, 

48 ``PeriodIndex.shift``. 

49 

50 See Also 

51 -------- 

52 Index.shift : Shift values of Index. 

53 Series.shift : Shift values of Series. 

54 

55 Examples 

56 -------- 

57 >>> df = pd.DatetimeIndex(["2011-01-01 10:00", "2011-01-01"], freq=None) 

58 >>> df.shift(2) 

59 Traceback (most recent call last): 

60 NullFrequencyError: Cannot shift with no freq 

61 """ 

62 

63 

64class PerformanceWarning(Warning): 

65 """ 

66 Warning raised when there is a possible performance impact. 

67 

68 See Also 

69 -------- 

70 DataFrame.set_index : Set the DataFrame index using existing columns. 

71 DataFrame.loc : Access a group of rows and columns by label(s) \ 

72 or a boolean array. 

73 

74 Examples 

75 -------- 

76 >>> df = pd.DataFrame( 

77 ... {"jim": [0, 0, 1, 1], "joe": ["x", "x", "z", "y"], "jolie": [1, 2, 3, 4]} 

78 ... ) 

79 >>> df = df.set_index(["jim", "joe"]) 

80 >>> df 

81 jolie 

82 jim joe 

83 0 x 1 

84 x 2 

85 1 z 3 

86 y 4 

87 >>> df.loc[(1, "z")] # doctest: +SKIP 

88 # PerformanceWarning: indexing past lexsort depth may impact performance. 

89 df.loc[(1, 'z')] 

90 jolie 

91 jim joe 

92 1 z 3 

93 """ 

94 

95 

96class PandasChangeWarning(Warning): 

97 """ 

98 Warning raised for any upcoming change. 

99 

100 See Also 

101 -------- 

102 errors.PandasPendingDeprecationWarning : Class for deprecations that will raise a 

103 PendingDeprecationWarning. 

104 errors.PandasDeprecationWarning : Class for deprecations that will raise a 

105 DeprecationWarning. 

106 errors.PandasFutureWarning : Class for deprecations that will raise a FutureWarning. 

107 

108 Examples 

109 -------- 

110 >>> pd.errors.PandasChangeWarning 

111 <class 'pandas.errors.PandasChangeWarning'> 

112 """ 

113 

114 @classmethod 

115 @abc.abstractmethod 

116 def version(cls) -> str: 

117 """Version where change will be enforced.""" 

118 

119 

120class PandasPendingDeprecationWarning(PandasChangeWarning, PendingDeprecationWarning): 

121 """ 

122 Warning raised for an upcoming change that is a PendingDeprecationWarning. 

123 

124 See Also 

125 -------- 

126 errors.PandasChangeWarning: Class for deprecations that will raise any warning. 

127 errors.PandasDeprecationWarning : Class for deprecations that will raise a 

128 DeprecationWarning. 

129 errors.PandasFutureWarning : Class for deprecations that will raise a FutureWarning. 

130 

131 Examples 

132 -------- 

133 >>> pd.errors.PandasPendingDeprecationWarning 

134 <class 'pandas.errors.PandasPendingDeprecationWarning'> 

135 """ 

136 

137 

138class PandasDeprecationWarning(PandasChangeWarning, DeprecationWarning): 

139 """ 

140 Warning raised for an upcoming change that is a DeprecationWarning. 

141 

142 See Also 

143 -------- 

144 errors.PandasChangeWarning: Class for deprecations that will raise any warning. 

145 errors.PandasPendingDeprecationWarning : Class for deprecations that will raise a 

146 PendingDeprecationWarning. 

147 errors.PandasFutureWarning : Class for deprecations that will raise a FutureWarning. 

148 

149 Examples 

150 -------- 

151 >>> pd.errors.PandasDeprecationWarning 

152 <class 'pandas.errors.PandasDeprecationWarning'> 

153 """ 

154 

155 

156class PandasFutureWarning(PandasChangeWarning, FutureWarning): 

157 """ 

158 Warning raised for an upcoming change that is a FutureWarning. 

159 

160 See Also 

161 -------- 

162 errors.PandasChangeWarning: Class for deprecations that will raise any warning. 

163 errors.PandasPendingDeprecationWarning : Class for deprecations that will raise a 

164 PendingDeprecationWarning. 

165 errors.PandasDeprecationWarning : Class for deprecations that will raise a 

166 DeprecationWarning. 

167 

168 Examples 

169 -------- 

170 >>> pd.errors.PandasFutureWarning 

171 <class 'pandas.errors.PandasFutureWarning'> 

172 """ 

173 

174 

175class Pandas4Warning(PandasDeprecationWarning): 

176 """ 

177 Warning raised for an upcoming change that will be enforced in pandas 4.0. 

178 

179 See Also 

180 -------- 

181 errors.PandasChangeWarning: Class for deprecations that will raise any warning. 

182 errors.PandasPendingDeprecationWarning : Class for deprecations that will raise a 

183 PendingDeprecationWarning. 

184 errors.PandasDeprecationWarning : Class for deprecations that will raise a 

185 DeprecationWarning. 

186 errors.PandasFutureWarning : Class for deprecations that will raise a FutureWarning. 

187 

188 Examples 

189 -------- 

190 >>> pd.errors.Pandas4Warning 

191 <class 'pandas.errors.Pandas4Warning'> 

192 """ 

193 

194 @classmethod 

195 def version(cls) -> str: 

196 """Version where change will be enforced.""" 

197 return "4.0" 

198 

199 

200class Pandas5Warning(PandasPendingDeprecationWarning): 

201 """ 

202 Warning raised for an upcoming change that will be enforced in pandas 5.0. 

203 

204 See Also 

205 -------- 

206 errors.PandasChangeWarning: Class for deprecations that will raise any warning. 

207 errors.PandasPendingDeprecationWarning : Class for deprecations that will raise a 

208 PendingDeprecationWarning. 

209 errors.PandasDeprecationWarning : Class for deprecations that will raise a 

210 DeprecationWarning. 

211 errors.PandasFutureWarning : Class for deprecations that will raise a FutureWarning. 

212 

213 Examples 

214 -------- 

215 >>> pd.errors.Pandas5Warning 

216 <class 'pandas.errors.Pandas5Warning'> 

217 """ 

218 

219 @classmethod 

220 def version(cls) -> str: 

221 """Version where change will be enforced.""" 

222 return "5.0" 

223 

224 

225_CurrentDeprecationWarning = Pandas4Warning 

226 

227 

228class UnsupportedFunctionCall(ValueError): 

229 """ 

230 Exception raised when attempting to call a unsupported numpy function. 

231 

232 For example, ``np.cumsum(groupby_object)``. 

233 

234 See Also 

235 -------- 

236 DataFrame.groupby : Group DataFrame using a mapper or by a Series of columns. 

237 Series.groupby : Group Series using a mapper or by a Series of columns. 

238 core.groupby.GroupBy.cumsum : Compute cumulative sum for each group. 

239 

240 Examples 

241 -------- 

242 >>> df = pd.DataFrame( 

243 ... {"A": [0, 0, 1, 1], "B": ["x", "x", "z", "y"], "C": [1, 2, 3, 4]} 

244 ... ) 

245 >>> np.cumsum(df.groupby(["A"])) 

246 Traceback (most recent call last): 

247 UnsupportedFunctionCall: numpy operations are not valid with groupby. 

248 Use .groupby(...).cumsum() instead 

249 """ 

250 

251 

252class UnsortedIndexError(KeyError): 

253 """ 

254 Error raised when slicing a MultiIndex which has not been lexsorted. 

255 

256 Subclass of `KeyError`. 

257 

258 See Also 

259 -------- 

260 DataFrame.sort_index : Sort a DataFrame by its index. 

261 DataFrame.set_index : Set the DataFrame index using existing columns. 

262 

263 Examples 

264 -------- 

265 >>> df = pd.DataFrame( 

266 ... { 

267 ... "cat": [0, 0, 1, 1], 

268 ... "color": ["white", "white", "brown", "black"], 

269 ... "lives": [4, 4, 3, 7], 

270 ... }, 

271 ... ) 

272 >>> df = df.set_index(["cat", "color"]) 

273 >>> df 

274 lives 

275 cat color 

276 0 white 4 

277 white 4 

278 1 brown 3 

279 black 7 

280 >>> df.loc[(0, "black") : (1, "white")] 

281 Traceback (most recent call last): 

282 UnsortedIndexError: 'Key length (2) was greater 

283 than MultiIndex lexsort depth (1)' 

284 """ 

285 

286 

287class ParserError(ValueError): 

288 """ 

289 Exception that is raised by an error encountered in parsing file contents. 

290 

291 This is a generic error raised for errors encountered when functions like 

292 `read_csv` or `read_html` are parsing contents of a file. 

293 

294 See Also 

295 -------- 

296 read_csv : Read CSV (comma-separated) file into a DataFrame. 

297 read_html : Read HTML table into a DataFrame. 

298 

299 Examples 

300 -------- 

301 >>> data = '''a,b,c 

302 ... cat,foo,bar 

303 ... dog,foo,"baz''' 

304 >>> from io import StringIO 

305 >>> pd.read_csv(StringIO(data), skipfooter=1, engine="python") 

306 Traceback (most recent call last): 

307 ParserError: ',' expected after '"'. Error could possibly be due 

308 to parsing errors in the skipped footer rows 

309 """ 

310 

311 

312class DtypeWarning(Warning): 

313 """ 

314 Warning raised when reading different dtypes in a column from a file. 

315 

316 Raised for a dtype incompatibility. This can happen whenever `read_csv` 

317 or `read_table` encounter non-uniform dtypes in a column(s) of a given 

318 CSV file. 

319 

320 See Also 

321 -------- 

322 read_csv : Read CSV (comma-separated) file into a DataFrame. 

323 read_table : Read general delimited file into a DataFrame. 

324 

325 Notes 

326 ----- 

327 This warning is issued when dealing with larger files because the dtype 

328 checking happens per chunk read. 

329 

330 Despite the warning, the CSV file is read with mixed types in a single 

331 column which will be an object type. See the examples below to better 

332 understand this issue. 

333 

334 Examples 

335 -------- 

336 This example creates and reads a large CSV file with a column that contains 

337 `int` and `str`. 

338 

339 >>> df = pd.DataFrame( 

340 ... { 

341 ... "a": (["1"] * 100000 + ["X"] * 100000 + ["1"] * 100000), 

342 ... "b": ["b"] * 300000, 

343 ... } 

344 ... ) # doctest: +SKIP 

345 >>> df.to_csv("test.csv", index=False) # doctest: +SKIP 

346 >>> df2 = pd.read_csv("test.csv") # doctest: +SKIP 

347 ... # DtypeWarning: Columns (0: a) have mixed types 

348 

349 Important to notice that ``df2`` will contain both `str` and `int` for the 

350 same input, '1'. 

351 

352 >>> df2.iloc[262140, 0] # doctest: +SKIP 

353 '1' 

354 >>> type(df2.iloc[262140, 0]) # doctest: +SKIP 

355 <class 'str'> 

356 >>> df2.iloc[262150, 0] # doctest: +SKIP 

357 1 

358 >>> type(df2.iloc[262150, 0]) # doctest: +SKIP 

359 <class 'int'> 

360 

361 One way to solve this issue is using the `dtype` parameter in the 

362 `read_csv` and `read_table` functions to explicit the conversion: 

363 

364 >>> df2 = pd.read_csv("test.csv", sep=",", dtype={"a": str}) # doctest: +SKIP 

365 

366 No warning was issued. 

367 """ 

368 

369 

370class EmptyDataError(ValueError): 

371 """ 

372 Exception raised in ``pd.read_csv`` when empty data or header is encountered. 

373 

374 This error is typically encountered when attempting to read an empty file or 

375 an invalid file where no data or headers are present. 

376 

377 See Also 

378 -------- 

379 read_csv : Read a comma-separated values (CSV) file into DataFrame. 

380 errors.ParserError : Exception that is raised by an error encountered in parsing 

381 file contents. 

382 errors.DtypeWarning : Warning raised when reading different dtypes in a column 

383 from a file. 

384 

385 Examples 

386 -------- 

387 >>> from io import StringIO 

388 >>> empty = StringIO() 

389 >>> pd.read_csv(empty) 

390 Traceback (most recent call last): 

391 EmptyDataError: No columns to parse from file 

392 """ 

393 

394 

395class ParserWarning(Warning): 

396 """ 

397 Warning raised when reading a file that doesn't use the default 'c' parser. 

398 

399 Raised by `pd.read_csv` and `pd.read_table` when it is necessary to change 

400 parsers, generally from the default 'c' parser to 'python'. 

401 

402 It happens due to a lack of support or functionality for parsing a 

403 particular attribute of a CSV file with the requested engine. 

404 

405 Currently, 'c' unsupported options include the following parameters: 

406 

407 1. `sep` other than a single character (e.g. regex separators) 

408 2. `skipfooter` higher than 0 

409 

410 The warning can be avoided by adding `engine='python'` as a parameter in 

411 `pd.read_csv` and `pd.read_table` methods. 

412 

413 See Also 

414 -------- 

415 pd.read_csv : Read CSV (comma-separated) file into DataFrame. 

416 pd.read_table : Read general delimited file into DataFrame. 

417 

418 Examples 

419 -------- 

420 Using a `sep` in `pd.read_csv` other than a single character: 

421 

422 >>> import io 

423 >>> csv = '''a;b;c 

424 ... 1;1,8 

425 ... 1;2,1''' 

426 >>> df = pd.read_csv(io.StringIO(csv), sep="[;,]") # doctest: +SKIP 

427 ... # ParserWarning: Falling back to the 'python' engine... 

428 

429 Adding `engine='python'` to `pd.read_csv` removes the Warning: 

430 

431 >>> df = pd.read_csv(io.StringIO(csv), sep="[;,]", engine="python") 

432 """ 

433 

434 

435class MergeError(ValueError): 

436 """ 

437 Exception raised when merging data. 

438 

439 Subclass of ``ValueError``. 

440 

441 See Also 

442 -------- 

443 DataFrame.join : For joining DataFrames on their indexes. 

444 merge : For merging two DataFrames on a common set of keys. 

445 

446 Examples 

447 -------- 

448 >>> left = pd.DataFrame( 

449 ... {"a": ["a", "b", "b", "d"], "b": ["cat", "dog", "weasel", "horse"]}, 

450 ... index=range(4), 

451 ... ) 

452 >>> right = pd.DataFrame( 

453 ... {"a": ["a", "b", "c", "d"], "c": ["meow", "bark", "chirp", "nay"]}, 

454 ... index=range(4), 

455 ... ).set_index("a") 

456 >>> left.join( 

457 ... right, 

458 ... on="a", 

459 ... validate="one_to_one", 

460 ... ) 

461 Traceback (most recent call last): 

462 MergeError: Merge keys are not unique in left dataset; not a one-to-one merge 

463 """ 

464 

465 

466class AbstractMethodError(NotImplementedError): 

467 """ 

468 Raise this error instead of NotImplementedError for abstract methods. 

469 

470 The `AbstractMethodError` is designed for use in classes that follow an abstract 

471 base class pattern. By raising this error in the method, it ensures that a subclass 

472 must implement the method to provide specific functionality. This is useful in a 

473 framework or library where certain methods must be implemented by the user to 

474 ensure correct behavior. 

475 

476 Parameters 

477 ---------- 

478 class_instance : object 

479 The instance of the class where the abstract method is being called. 

480 methodtype : str, default "method" 

481 A string indicating the type of method that is abstract. 

482 Must be one of {"method", "classmethod", "staticmethod", "property"}. 

483 

484 See Also 

485 -------- 

486 api.extensions.ExtensionArray 

487 An example of a pandas extension mechanism that requires implementing 

488 specific abstract methods. 

489 NotImplementedError 

490 A built-in exception that can also be used for abstract methods but lacks 

491 the specificity of `AbstractMethodError` in indicating the need for subclass 

492 implementation. 

493 

494 Examples 

495 -------- 

496 >>> class Foo: 

497 ... @classmethod 

498 ... def classmethod(cls): 

499 ... raise pd.errors.AbstractMethodError(cls, methodtype="classmethod") 

500 ... 

501 ... def method(self): 

502 ... raise pd.errors.AbstractMethodError(self) 

503 >>> test = Foo.classmethod() 

504 Traceback (most recent call last): 

505 AbstractMethodError: This classmethod must be defined in the concrete class Foo 

506 

507 >>> test2 = Foo().method() 

508 Traceback (most recent call last): 

509 AbstractMethodError: This classmethod must be defined in the concrete class Foo 

510 """ 

511 

512 def __init__(self, class_instance, methodtype: str = "method") -> None: 

513 types = {"method", "classmethod", "staticmethod", "property"} 

514 if methodtype not in types: 

515 raise ValueError( 

516 f"methodtype must be one of {types}, got {methodtype} instead." 

517 ) 

518 self.methodtype = methodtype 

519 self.class_instance = class_instance 

520 

521 def __str__(self) -> str: 

522 if self.methodtype == "classmethod": 

523 name = self.class_instance.__name__ 

524 else: 

525 name = type(self.class_instance).__name__ 

526 return f"This {self.methodtype} must be defined in the concrete class {name}" 

527 

528 

529class NumbaUtilError(Exception): 

530 """ 

531 Error raised for unsupported Numba engine routines. 

532 

533 See Also 

534 -------- 

535 DataFrame.groupby : Group DataFrame using a mapper or by a Series of columns. 

536 Series.groupby : Group Series using a mapper or by a Series of columns. 

537 DataFrame.agg : Aggregate using one or more operations over the specified axis. 

538 Series.agg : Aggregate using one or more operations over the specified axis. 

539 

540 Examples 

541 -------- 

542 >>> df = pd.DataFrame( 

543 ... {"key": ["a", "a", "b", "b"], "data": [1, 2, 3, 4]}, columns=["key", "data"] 

544 ... ) 

545 >>> def incorrect_function(x): 

546 ... return sum(x) * 2.7 

547 >>> df.groupby("key").agg(incorrect_function, engine="numba") 

548 Traceback (most recent call last): 

549 NumbaUtilError: The first 2 arguments to incorrect_function 

550 must be ['values', 'index'] 

551 """ 

552 

553 

554class DuplicateLabelError(ValueError): 

555 """ 

556 Error raised when an operation would introduce duplicate labels. 

557 

558 This error is typically encountered when performing operations on objects 

559 with `allows_duplicate_labels=False` and the operation would result in 

560 duplicate labels in the index. Duplicate labels can lead to ambiguities 

561 in indexing and reduce data integrity. 

562 

563 See Also 

564 -------- 

565 Series.set_flags : Return a new ``Series`` object with updated flags. 

566 DataFrame.set_flags : Return a new ``DataFrame`` object with updated flags. 

567 Series.reindex : Conform ``Series`` object to new index with optional filling logic. 

568 DataFrame.reindex : Conform ``DataFrame`` object to new index with optional filling 

569 logic. 

570 

571 Examples 

572 -------- 

573 >>> s = pd.Series([0, 1, 2], index=["a", "b", "c"]).set_flags( 

574 ... allows_duplicate_labels=False 

575 ... ) 

576 >>> s.reindex(["a", "a", "b"]) 

577 Traceback (most recent call last): 

578 ... 

579 DuplicateLabelError: Index has duplicates. 

580 positions 

581 label 

582 a [0, 1] 

583 """ 

584 

585 

586class InvalidIndexError(Exception): 

587 """ 

588 Exception raised when attempting to use an invalid index key. 

589 

590 This exception is triggered when a user attempts to access or manipulate 

591 data in a pandas DataFrame or Series using an index key that is not valid 

592 for the given object. This may occur in cases such as using a malformed 

593 slice, a mismatched key for a ``MultiIndex``, or attempting to access an index 

594 element that does not exist. 

595 

596 See Also 

597 -------- 

598 MultiIndex : A multi-level, or hierarchical, index object for pandas objects. 

599 

600 Examples 

601 -------- 

602 >>> idx = pd.MultiIndex.from_product([["x", "y"], [0, 1]]) 

603 >>> df = pd.DataFrame([[1, 1, 2, 2], [3, 3, 4, 4]], columns=idx) 

604 >>> df 

605 x y 

606 0 1 0 1 

607 0 1 1 2 2 

608 1 3 3 4 4 

609 >>> df[:, 0] 

610 Traceback (most recent call last): 

611 InvalidIndexError: (slice(None, None, None), 0) 

612 """ 

613 

614 

615class DataError(Exception): 

616 """ 

617 Exception raised when performing an operation on non-numerical data. 

618 

619 For example, calling ``ohlc`` on a non-numerical column or a function 

620 on a rolling window. 

621 

622 See Also 

623 -------- 

624 Series.rolling : Provide rolling window calculations on Series object. 

625 DataFrame.rolling : Provide rolling window calculations on DataFrame object. 

626 

627 Examples 

628 -------- 

629 >>> ser = pd.Series(["a", "b", "c"]) 

630 >>> ser.rolling(2).sum() 

631 Traceback (most recent call last): 

632 DataError: No numeric types to aggregate 

633 """ 

634 

635 

636class SpecificationError(Exception): 

637 """ 

638 Exception raised by ``agg`` when the functions are ill-specified. 

639 

640 The exception raised in two scenarios. 

641 

642 The first way is calling ``agg`` on a 

643 Dataframe or Series using a nested renamer (dict-of-dict). 

644 

645 The second way is calling ``agg`` on a Dataframe with duplicated functions 

646 names without assigning column name. 

647 

648 See Also 

649 -------- 

650 DataFrame.agg : Aggregate using one or more operations over the specified axis. 

651 Series.agg : Aggregate using one or more operations over the specified axis. 

652 

653 Examples 

654 -------- 

655 >>> df = pd.DataFrame({"A": [1, 1, 1, 2, 2], "B": range(5), "C": range(5)}) 

656 >>> df.groupby("A").B.agg({"foo": "count"}) # doctest: +SKIP 

657 ... # SpecificationError: nested renamer is not supported 

658 

659 >>> df.groupby("A").agg({"B": {"foo": ["sum", "max"]}}) # doctest: +SKIP 

660 ... # SpecificationError: nested renamer is not supported 

661 

662 >>> df.groupby("A").agg(["min", "min"]) # doctest: +SKIP 

663 ... # SpecificationError: nested renamer is not supported 

664 """ 

665 

666 

667class ChainedAssignmentError(Warning): 

668 """ 

669 Warning raised when trying to set using chained assignment. 

670 

671 With Copy-on-Write now always enabled, chained assignment can 

672 never work. In such a situation, we are always setting into a temporary 

673 object that is the result of an indexing operation (getitem), which under 

674 Copy-on-Write always behaves as a copy. Thus, assigning through a chain 

675 can never update the original Series or DataFrame. 

676 

677 For more information on Copy-on-Write, 

678 see :ref:`the user guide<copy_on_write>`. 

679 

680 See Also 

681 -------- 

682 DataFrame.loc : Access a group of rows and columns by label(s) or a boolean array. 

683 DataFrame.iloc : Purely integer-location based indexing for selection by position. 

684 Series.loc : Access a group of rows by label(s) or a boolean array. 

685 

686 Examples 

687 -------- 

688 >>> df = pd.DataFrame({"A": [1, 1, 1, 2, 2]}, columns=["A"]) 

689 >>> df["A"][0:3] = 10 # doctest: +SKIP 

690 ... # ChainedAssignmentError: ... 

691 """ 

692 

693 

694class NumExprClobberingError(NameError): 

695 """ 

696 Exception raised when trying to use a built-in numexpr name as a variable name. 

697 

698 ``eval`` or ``query`` will throw the error if the engine is set 

699 to 'numexpr'. 'numexpr' is the default engine value for these methods if the 

700 numexpr package is installed. 

701 

702 See Also 

703 -------- 

704 eval : Evaluate a Python expression as a string using various backends. 

705 DataFrame.query : Query the columns of a DataFrame with a boolean expression. 

706 

707 Examples 

708 -------- 

709 >>> df = pd.DataFrame({"abs": [1, 1, 1]}) 

710 >>> df.query("abs > 2") # doctest: +SKIP 

711 ... # NumExprClobberingError: Variables in expression "(abs) > (2)" overlap... 

712 >>> sin, a = 1, 2 

713 >>> pd.eval("sin + a", engine="numexpr") # doctest: +SKIP 

714 ... # NumExprClobberingError: Variables in expression "(sin) + (a)" overlap... 

715 """ 

716 

717 

718class UndefinedVariableError(NameError): 

719 """ 

720 Exception raised by ``query`` or ``eval`` when using an undefined variable name. 

721 

722 It will also specify whether the undefined variable is local or not. 

723 

724 Parameters 

725 ---------- 

726 name : str 

727 The name of the undefined variable. 

728 is_local : bool or None, optional 

729 Indicates whether the undefined variable is considered a local variable. 

730 If ``True``, the error message specifies it as a local variable. 

731 If ``False`` or ``None``, the variable is treated as a non-local name. 

732 

733 See Also 

734 -------- 

735 DataFrame.query : Query the columns of a DataFrame with a boolean expression. 

736 DataFrame.eval : Evaluate a string describing operations on DataFrame columns. 

737 

738 Examples 

739 -------- 

740 >>> df = pd.DataFrame({"A": [1, 1, 1]}) 

741 >>> df.query("A > x") # doctest: +SKIP 

742 ... # UndefinedVariableError: name 'x' is not defined 

743 >>> df.query("A > @y") # doctest: +SKIP 

744 ... # UndefinedVariableError: local variable 'y' is not defined 

745 >>> pd.eval("x + 1") # doctest: +SKIP 

746 ... # UndefinedVariableError: name 'x' is not defined 

747 """ 

748 

749 def __init__(self, name: str, is_local: bool | None = None) -> None: 

750 base_msg = f"{name!r} is not defined" 

751 if is_local: 

752 msg = f"local variable {base_msg}" 

753 else: 

754 msg = f"name {base_msg}" 

755 super().__init__(msg) 

756 

757 

758class IndexingError(Exception): 

759 """ 

760 Exception is raised when trying to index and there is a mismatch in dimensions. 

761 

762 Raised by properties like :attr:`.pandas.DataFrame.iloc` when 

763 an indexer is out of bounds or :attr:`.pandas.DataFrame.loc` when its index is 

764 unalignable to the frame index. 

765 

766 See Also 

767 -------- 

768 DataFrame.iloc : Purely integer-location based indexing for \ 

769 selection by position. 

770 DataFrame.loc : Access a group of rows and columns by label(s) \ 

771 or a boolean array. 

772 

773 Examples 

774 -------- 

775 >>> df = pd.DataFrame({"A": [1, 1, 1]}) 

776 >>> df.loc[..., ..., "A"] # doctest: +SKIP 

777 ... # IndexingError: indexer may only contain one '...' entry 

778 >>> df = pd.DataFrame({"A": [1, 1, 1]}) 

779 >>> df.loc[1, ..., ...] # doctest: +SKIP 

780 ... # IndexingError: Too many indexers 

781 >>> df[pd.Series([True], dtype=bool)] # doctest: +SKIP 

782 ... # IndexingError: Unalignable boolean Series provided as indexer... 

783 >>> s = pd.Series(range(2), index=pd.MultiIndex.from_product([["a", "b"], ["c"]])) 

784 >>> s.loc["a", "c", "d"] # doctest: +SKIP 

785 ... # IndexingError: Too many indexers 

786 """ 

787 

788 

789class PyperclipException(RuntimeError): 

790 """ 

791 Exception raised when clipboard functionality is unsupported. 

792 

793 Raised by ``to_clipboard()`` and ``read_clipboard()``. 

794 """ 

795 

796 

797class PyperclipWindowsException(PyperclipException): 

798 """ 

799 Exception raised when clipboard functionality is unsupported by Windows. 

800 

801 Access to the clipboard handle would be denied due to some other 

802 window process is accessing it. 

803 """ 

804 

805 def __init__(self, message: str) -> None: 

806 # attr only exists on Windows, so typing fails on other platforms 

807 message += f" ({ctypes.WinError()})" # type: ignore[attr-defined] 

808 super().__init__(message) 

809 

810 

811class CSSWarning(UserWarning): 

812 """ 

813 Warning is raised when converting css styling fails. 

814 

815 This can be due to the styling not having an equivalent value or because the 

816 styling isn't properly formatted. 

817 

818 See Also 

819 -------- 

820 DataFrame.style : Returns a Styler object for applying CSS-like styles. 

821 io.formats.style.Styler : Helps style a DataFrame or Series according to the 

822 data with HTML and CSS. 

823 io.formats.style.Styler.to_excel : Export styled DataFrame to Excel. 

824 io.formats.style.Styler.to_html : Export styled DataFrame to HTML. 

825 

826 Examples 

827 -------- 

828 >>> df = pd.DataFrame({"A": [1, 1, 1]}) 

829 >>> df.style.map(lambda x: "background-color: blueGreenRed;").to_excel( 

830 ... "styled.xlsx" 

831 ... ) # doctest: +SKIP 

832 CSSWarning: Unhandled color format: 'blueGreenRed' 

833 >>> df.style.map(lambda x: "border: 1px solid red red;").to_excel( 

834 ... "styled.xlsx" 

835 ... ) # doctest: +SKIP 

836 CSSWarning: Unhandled color format: 'blueGreenRed' 

837 """ 

838 

839 

840class PossibleDataLossError(Exception): 

841 """ 

842 Exception raised when trying to open an HDFStore file when already opened. 

843 

844 This error is triggered when there is a potential risk of data loss due to 

845 conflicting operations on an HDFStore file. It serves to prevent unintended 

846 overwrites or data corruption by enforcing exclusive access to the file. 

847 

848 See Also 

849 -------- 

850 HDFStore : Dict-like IO interface for storing pandas objects in PyTables. 

851 HDFStore.open : Open an HDFStore file in the specified mode. 

852 

853 Examples 

854 -------- 

855 >>> store = pd.HDFStore("my-store", "a") # doctest: +SKIP 

856 >>> store.open("w") # doctest: +SKIP 

857 """ 

858 

859 

860class ClosedFileError(Exception): 

861 """ 

862 Exception is raised when trying to perform an operation on a closed HDFStore file. 

863 

864 ``ClosedFileError`` is specific to operations on ``HDFStore`` objects. Once an 

865 HDFStore is closed, its resources are no longer available, and any further attempt 

866 to access data or perform file operations will raise this exception. 

867 

868 See Also 

869 -------- 

870 HDFStore.close : Closes the PyTables file handle. 

871 HDFStore.open : Opens the file in the specified mode. 

872 HDFStore.is_open : Returns a boolean indicating whether the file is open. 

873 

874 Examples 

875 -------- 

876 >>> store = pd.HDFStore("my-store", "a") # doctest: +SKIP 

877 >>> store.close() # doctest: +SKIP 

878 >>> store.keys() # doctest: +SKIP 

879 ... # ClosedFileError: my-store file is not open! 

880 """ 

881 

882 

883class IncompatibilityWarning(Warning): 

884 """ 

885 Warning raised when trying to use where criteria on an incompatible HDF5 file. 

886 """ 

887 

888 

889class AttributeConflictWarning(Warning): 

890 """ 

891 Warning raised when index attributes conflict when using HDFStore. 

892 

893 Occurs when attempting to append an index with a different 

894 name than the existing index on an HDFStore or attempting to append an index with a 

895 different frequency than the existing index on an HDFStore. 

896 

897 See Also 

898 -------- 

899 HDFStore : Dict-like IO interface for storing pandas objects in PyTables. 

900 DataFrame.to_hdf : Write the contained data to an HDF5 file using HDFStore. 

901 read_hdf : Read from an HDF5 file into a DataFrame. 

902 

903 Examples 

904 -------- 

905 >>> idx1 = pd.Index(["a", "b"], name="name1") 

906 >>> df1 = pd.DataFrame([[1, 2], [3, 4]], index=idx1) 

907 >>> df1.to_hdf("file", "data", "w", append=True) # doctest: +SKIP 

908 >>> idx2 = pd.Index(["c", "d"], name="name2") 

909 >>> df2 = pd.DataFrame([[5, 6], [7, 8]], index=idx2) 

910 >>> df2.to_hdf("file", "data", "a", append=True) # doctest: +SKIP 

911 AttributeConflictWarning: the [index_name] attribute of the existing index is 

912 [name1] which conflicts with the new [name2]... 

913 """ 

914 

915 

916class DatabaseError(OSError): 

917 """ 

918 Error is raised when executing SQL with bad syntax or SQL that throws an error. 

919 

920 Raised by :func:`.pandas.read_sql` when a bad SQL statement is passed in. 

921 

922 See Also 

923 -------- 

924 read_sql : Read SQL query or database table into a DataFrame. 

925 

926 Examples 

927 -------- 

928 >>> from sqlite3 import connect 

929 >>> conn = connect(":memory:") 

930 >>> pd.read_sql("select * test", conn) # doctest: +SKIP 

931 """ 

932 

933 

934class PossiblePrecisionLoss(Warning): 

935 """ 

936 Warning raised by to_stata on a column with a value outside or equal to int64. 

937 

938 When the column value is outside or equal to the int64 value the column is 

939 converted to a float64 dtype. 

940 

941 See Also 

942 -------- 

943 DataFrame.to_stata : Export DataFrame object to Stata dta format. 

944 

945 Examples 

946 -------- 

947 >>> df = pd.DataFrame({"s": pd.Series([1, 2**53], dtype=np.int64)}) 

948 >>> df.to_stata("test") # doctest: +SKIP 

949 """ 

950 

951 

952class ValueLabelTypeMismatch(Warning): 

953 """ 

954 Warning raised by to_stata on a category column that contains non-string values. 

955 

956 When exporting data to Stata format using the `to_stata` method, category columns 

957 must have string values as labels. If a category column contains non-string values 

958 (e.g., integers, floats, or other types), this warning is raised to indicate that 

959 the Stata file may not correctly represent the data. 

960 

961 See Also 

962 -------- 

963 DataFrame.to_stata : Export DataFrame object to Stata dta format. 

964 Series.cat : Accessor for categorical properties of the Series values. 

965 

966 Examples 

967 -------- 

968 >>> df = pd.DataFrame({"categories": pd.Series(["a", 2], dtype="category")}) 

969 >>> df.to_stata("test") # doctest: +SKIP 

970 """ 

971 

972 

973class InvalidColumnName(Warning): 

974 """ 

975 Warning raised by to_stata the column contains a non-valid stata name. 

976 

977 Because the column name is an invalid Stata variable, the name needs to be 

978 converted. 

979 

980 See Also 

981 -------- 

982 DataFrame.to_stata : Export DataFrame object to Stata dta format. 

983 

984 Examples 

985 -------- 

986 >>> df = pd.DataFrame({"0categories": pd.Series([2, 2])}) 

987 >>> df.to_stata("test") # doctest: +SKIP 

988 """ 

989 

990 

991class CategoricalConversionWarning(Warning): 

992 """ 

993 Warning is raised when reading a partial labeled Stata file using an iterator. 

994 

995 This warning helps ensure data integrity and alerts users to potential issues 

996 during the incremental reading of Stata files with labeled data, allowing for 

997 additional checks and adjustments as necessary. 

998 

999 See Also 

1000 -------- 

1001 read_stata : Read a Stata file into a DataFrame. 

1002 Categorical : Represents a categorical variable in pandas. 

1003 

1004 Examples 

1005 -------- 

1006 >>> from pandas.io.stata import StataReader 

1007 >>> with StataReader("dta_file", chunksize=2) as reader: # doctest: +SKIP 

1008 ... for i, block in enumerate(reader): 

1009 ... print(i, block) 

1010 ... # CategoricalConversionWarning: One or more series with value labels... 

1011 """ 

1012 

1013 

1014class LossySetitemError(Exception): 

1015 """ 

1016 Raised when trying to do a __setitem__ on an np.ndarray that is not lossless. 

1017 

1018 Notes 

1019 ----- 

1020 This is an internal error. 

1021 """ 

1022 

1023 

1024class NoBufferPresent(Exception): 

1025 """ 

1026 Exception is raised in _get_data_buffer to signal that there is no requested buffer. 

1027 """ 

1028 

1029 

1030class InvalidComparison(Exception): 

1031 """ 

1032 Exception is raised by _validate_comparison_value to indicate an invalid comparison. 

1033 

1034 Notes 

1035 ----- 

1036 This is an internal error. 

1037 """ 

1038 

1039 

1040__all__ = [ 

1041 "AbstractMethodError", 

1042 "AttributeConflictWarning", 

1043 "CSSWarning", 

1044 "CategoricalConversionWarning", 

1045 "ChainedAssignmentError", 

1046 "ClosedFileError", 

1047 "DataError", 

1048 "DatabaseError", 

1049 "DtypeWarning", 

1050 "DuplicateLabelError", 

1051 "EmptyDataError", 

1052 "IncompatibilityWarning", 

1053 "IncompatibleFrequency", 

1054 "IndexingError", 

1055 "IntCastingNaNError", 

1056 "InvalidColumnName", 

1057 "InvalidComparison", 

1058 "InvalidIndexError", 

1059 "InvalidVersion", 

1060 "LossySetitemError", 

1061 "MergeError", 

1062 "NoBufferPresent", 

1063 "NullFrequencyError", 

1064 "NumExprClobberingError", 

1065 "NumbaUtilError", 

1066 "OptionError", 

1067 "OutOfBoundsDatetime", 

1068 "OutOfBoundsTimedelta", 

1069 "Pandas4Warning", 

1070 "Pandas5Warning", 

1071 "PandasChangeWarning", 

1072 "PandasDeprecationWarning", 

1073 "PandasFutureWarning", 

1074 "PandasPendingDeprecationWarning", 

1075 "ParserError", 

1076 "ParserWarning", 

1077 "PerformanceWarning", 

1078 "PossibleDataLossError", 

1079 "PossiblePrecisionLoss", 

1080 "PyperclipException", 

1081 "PyperclipWindowsException", 

1082 "SpecificationError", 

1083 "UndefinedVariableError", 

1084 "UnsortedIndexError", 

1085 "UnsupportedFunctionCall", 

1086 "ValueLabelTypeMismatch", 

1087]