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 This warning is typically raised when an operation may be slower than 

69 expected due to the data structure or access pattern being used. 

70 

71 See Also 

72 -------- 

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

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

75 or a boolean array. 

76 

77 Examples 

78 -------- 

79 >>> df = pd.DataFrame( 

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

81 ... ) 

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

83 >>> df 

84 jolie 

85 jim joe 

86 0 x 1 

87 x 2 

88 1 z 3 

89 y 4 

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

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

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

93 jolie 

94 jim joe 

95 1 z 3 

96 """ 

97 

98 

99class PandasChangeWarning(Warning): 

100 """ 

101 Warning raised for any upcoming change. 

102 

103 This is the base class for all pandas warnings that indicate upcoming 

104 changes to the library's behavior. 

105 

106 See Also 

107 -------- 

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

109 PendingDeprecationWarning. 

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

111 DeprecationWarning. 

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

113 

114 Examples 

115 -------- 

116 >>> pd.errors.PandasChangeWarning 

117 <class 'pandas.errors.PandasChangeWarning'> 

118 """ 

119 

120 @classmethod 

121 @abc.abstractmethod 

122 def version(cls) -> str: 

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

124 

125 

126class PandasPendingDeprecationWarning(PandasChangeWarning, PendingDeprecationWarning): 

127 """ 

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

129 

130 This warning indicates a feature that will be deprecated in a future 

131 version of pandas, but is not yet officially deprecated. 

132 

133 See Also 

134 -------- 

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

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

137 DeprecationWarning. 

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

139 

140 Examples 

141 -------- 

142 >>> pd.errors.PandasPendingDeprecationWarning 

143 <class 'pandas.errors.PandasPendingDeprecationWarning'> 

144 """ 

145 

146 

147class PandasDeprecationWarning(PandasChangeWarning, DeprecationWarning): 

148 """ 

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

150 

151 This warning indicates a feature that is officially deprecated and will 

152 be removed in a future version of pandas. 

153 

154 See Also 

155 -------- 

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

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

158 PendingDeprecationWarning. 

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

160 

161 Examples 

162 -------- 

163 >>> pd.errors.PandasDeprecationWarning 

164 <class 'pandas.errors.PandasDeprecationWarning'> 

165 """ 

166 

167 

168class PandasFutureWarning(PandasChangeWarning, FutureWarning): 

169 """ 

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

171 

172 This warning indicates a change in behavior that will occur in a future 

173 version of pandas. Users should update their code accordingly. 

174 

175 See Also 

176 -------- 

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

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

179 PendingDeprecationWarning. 

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

181 DeprecationWarning. 

182 

183 Examples 

184 -------- 

185 >>> pd.errors.PandasFutureWarning 

186 <class 'pandas.errors.PandasFutureWarning'> 

187 """ 

188 

189 

190class Pandas4Warning(PandasDeprecationWarning): 

191 """ 

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

193 

194 This warning indicates a deprecation that will be enforced when pandas 

195 version 4.0 is released. Users should update their code before upgrading. 

196 

197 See Also 

198 -------- 

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

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

201 PendingDeprecationWarning. 

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

203 DeprecationWarning. 

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

205 

206 Examples 

207 -------- 

208 >>> pd.errors.Pandas4Warning 

209 <class 'pandas.errors.Pandas4Warning'> 

210 """ 

211 

212 @classmethod 

213 def version(cls) -> str: 

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

215 return "4.0" 

216 

217 

218class Pandas5Warning(PandasPendingDeprecationWarning): 

219 """ 

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

221 

222 This warning indicates a pending deprecation that will be enforced when 

223 pandas version 5.0 is released. Users should plan to update their code. 

224 

225 See Also 

226 -------- 

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

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

229 PendingDeprecationWarning. 

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

231 DeprecationWarning. 

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

233 

234 Examples 

235 -------- 

236 >>> pd.errors.Pandas5Warning 

237 <class 'pandas.errors.Pandas5Warning'> 

238 """ 

239 

240 @classmethod 

241 def version(cls) -> str: 

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

243 return "5.0" 

244 

245 

246_CurrentDeprecationWarning = Pandas4Warning 

247 

248 

249class UnsupportedFunctionCall(ValueError): 

250 """ 

251 Exception raised when attempting to call an unsupported numpy function. 

252 

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

254 

255 See Also 

256 -------- 

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

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

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

260 

261 Examples 

262 -------- 

263 >>> df = pd.DataFrame( 

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

265 ... ) 

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

267 Traceback (most recent call last): 

268 UnsupportedFunctionCall: numpy operations are not valid with groupby. 

269 Use .groupby(...).cumsum() instead 

270 """ 

271 

272 

273class UnsortedIndexError(KeyError): 

274 """ 

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

276 

277 Subclass of `KeyError`. 

278 

279 See Also 

280 -------- 

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

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

283 

284 Examples 

285 -------- 

286 >>> df = pd.DataFrame( 

287 ... { 

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

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

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

291 ... }, 

292 ... ) 

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

294 >>> df 

295 lives 

296 cat color 

297 0 white 4 

298 white 4 

299 1 brown 3 

300 black 7 

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

302 Traceback (most recent call last): 

303 UnsortedIndexError: 'Key length (2) was greater 

304 than MultiIndex lexsort depth (1)' 

305 """ 

306 

307 

308class ParserError(ValueError): 

309 """ 

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

311 

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

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

314 

315 See Also 

316 -------- 

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

318 read_html : Read HTML table into a DataFrame. 

319 

320 Examples 

321 -------- 

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

323 ... cat,foo,bar 

324 ... dog,foo,"baz''' 

325 >>> from io import StringIO 

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

327 Traceback (most recent call last): 

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

329 to parsing errors in the skipped footer rows 

330 """ 

331 

332 

333class DtypeWarning(Warning): 

334 """ 

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

336 

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

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

339 CSV file. 

340 

341 See Also 

342 -------- 

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

344 read_table : Read general delimited file into a DataFrame. 

345 

346 Notes 

347 ----- 

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

349 checking happens per chunk read. 

350 

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

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

353 understand this issue. 

354 

355 Examples 

356 -------- 

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

358 `int` and `str`. 

359 

360 >>> df = pd.DataFrame( 

361 ... { 

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

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

364 ... } 

365 ... ) # doctest: +SKIP 

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

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

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

369 

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

371 same input, '1'. 

372 

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

374 '1' 

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

376 <class 'str'> 

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

378 1 

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

380 <class 'int'> 

381 

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

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

384 

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

386 

387 No warning was issued. 

388 """ 

389 

390 

391class EmptyDataError(ValueError): 

392 """ 

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

394 

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

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

397 

398 See Also 

399 -------- 

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

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

402 file contents. 

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

404 from a file. 

405 

406 Examples 

407 -------- 

408 >>> from io import StringIO 

409 >>> empty = StringIO() 

410 >>> pd.read_csv(empty) 

411 Traceback (most recent call last): 

412 EmptyDataError: No columns to parse from file 

413 """ 

414 

415 

416class ParserWarning(Warning): 

417 """ 

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

419 

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

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

422 

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

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

425 

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

427 

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

429 2. `skipfooter` higher than 0 

430 

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

432 `pd.read_csv` and `pd.read_table` methods. 

433 

434 See Also 

435 -------- 

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

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

438 

439 Examples 

440 -------- 

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

442 

443 >>> import io 

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

445 ... 1;1,8 

446 ... 1;2,1''' 

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

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

449 

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

451 

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

453 """ 

454 

455 

456class MergeError(ValueError): 

457 """ 

458 Exception raised when merging data. 

459 

460 Subclass of ``ValueError``. 

461 

462 See Also 

463 -------- 

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

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

466 

467 Examples 

468 -------- 

469 >>> left = pd.DataFrame( 

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

471 ... index=range(4), 

472 ... ) 

473 >>> right = pd.DataFrame( 

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

475 ... index=range(4), 

476 ... ).set_index("a") 

477 >>> left.join( 

478 ... right, 

479 ... on="a", 

480 ... validate="one_to_one", 

481 ... ) 

482 Traceback (most recent call last): 

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

484 """ 

485 

486 

487class AbstractMethodError(NotImplementedError): 

488 """ 

489 Raise this error instead of NotImplementedError for abstract methods. 

490 

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

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

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

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

495 ensure correct behavior. 

496 

497 Parameters 

498 ---------- 

499 class_instance : object 

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

501 methodtype : str, default "method" 

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

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

504 

505 See Also 

506 -------- 

507 api.extensions.ExtensionArray 

508 An example of a pandas extension mechanism that requires implementing 

509 specific abstract methods. 

510 NotImplementedError 

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

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

513 implementation. 

514 

515 Examples 

516 -------- 

517 >>> class Foo: 

518 ... @classmethod 

519 ... def classmethod(cls): 

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

521 ... 

522 ... def method(self): 

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

524 >>> test = Foo.classmethod() 

525 Traceback (most recent call last): 

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

527 

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

529 Traceback (most recent call last): 

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

531 """ 

532 

533 def __init__( 

534 self, class_instance: type | object, methodtype: str = "method" 

535 ) -> None: 

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

537 if methodtype not in types: 

538 raise ValueError( 

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

540 ) 

541 self.methodtype = methodtype 

542 self.class_instance = class_instance 

543 

544 def __str__(self) -> str: 

545 if isinstance(self.class_instance, type): 

546 name = self.class_instance.__name__ 

547 else: 

548 name = type(self.class_instance).__name__ 

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

550 

551 

552class NumbaUtilError(Exception): 

553 """ 

554 Error raised for unsupported Numba engine routines. 

555 

556 This exception is raised when attempting to use the Numba engine with 

557 a function or operation that is not supported by Numba. 

558 

559 See Also 

560 -------- 

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

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

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

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

565 

566 Examples 

567 -------- 

568 >>> df = pd.DataFrame( 

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

570 ... ) 

571 >>> def incorrect_function(x): 

572 ... return sum(x) * 2.7 

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

574 Traceback (most recent call last): 

575 NumbaUtilError: The first 2 arguments to incorrect_function 

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

577 """ 

578 

579 

580class DuplicateLabelError(ValueError): 

581 """ 

582 Error raised when an operation would introduce duplicate labels. 

583 

584 This error is typically encountered when performing operations on objects 

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

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

587 in indexing and reduce data integrity. 

588 

589 See Also 

590 -------- 

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

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

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

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

595 logic. 

596 

597 Examples 

598 -------- 

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

600 ... allows_duplicate_labels=False 

601 ... ) 

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

603 Traceback (most recent call last): 

604 ... 

605 DuplicateLabelError: Index has duplicates. 

606 positions 

607 label 

608 a [0, 1] 

609 """ 

610 

611 

612class InvalidIndexError(Exception): 

613 """ 

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

615 

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

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

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

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

620 element that does not exist. 

621 

622 See Also 

623 -------- 

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

625 

626 Examples 

627 -------- 

628 >>> df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) 

629 >>> df[("a", slice(None))] 

630 Traceback (most recent call last): 

631 InvalidIndexError: ('a', slice(None, None, None)) 

632 """ 

633 

634 

635class DataError(Exception): 

636 """ 

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

638 

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

640 on a rolling window. 

641 

642 See Also 

643 -------- 

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

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

646 

647 Examples 

648 -------- 

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

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

651 Traceback (most recent call last): 

652 DataError: No numeric types to aggregate 

653 """ 

654 

655 

656class SpecificationError(Exception): 

657 """ 

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

659 

660 The exception raised in two scenarios. 

661 

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

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

664 

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

666 names without assigning column name. 

667 

668 See Also 

669 -------- 

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

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

672 

673 Examples 

674 -------- 

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

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

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

678 

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

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

681 

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

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

684 """ 

685 

686 

687class ChainedAssignmentError(Warning): 

688 """ 

689 Warning raised when trying to set using chained assignment. 

690 

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

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

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

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

695 can never update the original Series or DataFrame. 

696 

697 For more information on Copy-on-Write, 

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

699 

700 See Also 

701 -------- 

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

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

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

705 

706 Examples 

707 -------- 

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

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

710 ... # ChainedAssignmentError: ... 

711 """ 

712 

713 

714class NumExprClobberingError(NameError): 

715 """ 

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

717 

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

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

720 numexpr package is installed. 

721 

722 See Also 

723 -------- 

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

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

726 

727 Examples 

728 -------- 

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

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

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

732 >>> sin, a = 1, 2 

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

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

735 """ 

736 

737 

738class UndefinedVariableError(NameError): 

739 """ 

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

741 

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

743 

744 Parameters 

745 ---------- 

746 name : str 

747 The name of the undefined variable. 

748 is_local : bool or None, optional 

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

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

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

752 

753 See Also 

754 -------- 

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

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

757 

758 Examples 

759 -------- 

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

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

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

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

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

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

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

767 """ 

768 

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

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

771 if is_local: 

772 msg = f"local variable {base_msg}" 

773 else: 

774 msg = f"name {base_msg}" 

775 super().__init__(msg) 

776 

777 

778class IndexingError(Exception): 

779 """ 

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

781 

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

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

784 unalignable to the frame index. 

785 

786 See Also 

787 -------- 

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

789 selection by position. 

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

791 or a boolean array. 

792 

793 Examples 

794 -------- 

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

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

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

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

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

800 ... # IndexingError: Too many indexers 

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

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

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

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

805 ... # IndexingError: Too many indexers 

806 """ 

807 

808 

809class PyperclipException(RuntimeError): 

810 """ 

811 Exception raised when clipboard functionality is unsupported. 

812 

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

814 """ 

815 

816 

817class PyperclipWindowsException(PyperclipException): 

818 """ 

819 Exception raised when clipboard functionality is unsupported by Windows. 

820 

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

822 window process is accessing it. 

823 """ 

824 

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

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

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

828 super().__init__(message) 

829 

830 

831class CSSWarning(UserWarning): 

832 """ 

833 Warning is raised when converting css styling fails. 

834 

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

836 styling isn't properly formatted. 

837 

838 See Also 

839 -------- 

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

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

842 data with HTML and CSS. 

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

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

845 

846 Examples 

847 -------- 

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

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

850 ... "styled.xlsx" 

851 ... ) # doctest: +SKIP 

852 CSSWarning: Unhandled color format: 'blueGreenRed' 

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

854 ... "styled.xlsx" 

855 ... ) # doctest: +SKIP 

856 CSSWarning: Unhandled color format: 'blueGreenRed' 

857 """ 

858 

859 

860class PossibleDataLossError(Exception): 

861 """ 

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

863 

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

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

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

867 

868 See Also 

869 -------- 

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

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

872 

873 Examples 

874 -------- 

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

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

877 """ 

878 

879 

880class ClosedFileError(Exception): 

881 """ 

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

883 

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

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

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

887 

888 See Also 

889 -------- 

890 HDFStore.close : Closes the PyTables file handle. 

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

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

893 

894 Examples 

895 -------- 

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

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

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

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

900 """ 

901 

902 

903class IncompatibilityWarning(Warning): 

904 """ 

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

906 """ 

907 

908 

909class AttributeConflictWarning(Warning): 

910 """ 

911 Warning raised when index attributes conflict when using HDFStore. 

912 

913 Occurs when attempting to append an index with a different 

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

915 different frequency than the existing index on an HDFStore. 

916 

917 See Also 

918 -------- 

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

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

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

922 

923 Examples 

924 -------- 

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

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

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

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

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

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

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

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

933 """ 

934 

935 

936class DatabaseError(OSError): 

937 """ 

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

939 

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

941 

942 See Also 

943 -------- 

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

945 

946 Examples 

947 -------- 

948 >>> from sqlite3 import connect 

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

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

951 """ 

952 

953 

954class PossiblePrecisionLoss(Warning): 

955 """ 

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

957 

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

959 converted to a float64 dtype. 

960 

961 See Also 

962 -------- 

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

964 

965 Examples 

966 -------- 

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

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

969 """ 

970 

971 

972class ValueLabelTypeMismatch(Warning): 

973 """ 

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

975 

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

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

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

979 the Stata file may not correctly represent the data. 

980 

981 See Also 

982 -------- 

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

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

985 

986 Examples 

987 -------- 

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

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

990 """ 

991 

992 

993class InvalidColumnName(Warning): 

994 """ 

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

996 

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

998 converted. 

999 

1000 See Also 

1001 -------- 

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

1003 

1004 Examples 

1005 -------- 

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

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

1008 """ 

1009 

1010 

1011class CategoricalConversionWarning(Warning): 

1012 """ 

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

1014 

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

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

1017 additional checks and adjustments as necessary. 

1018 

1019 See Also 

1020 -------- 

1021 read_stata : Read a Stata file into a DataFrame. 

1022 Categorical : Represents a categorical variable in pandas. 

1023 

1024 Examples 

1025 -------- 

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

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

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

1029 ... print(i, block) 

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

1031 """ 

1032 

1033 

1034class LossySetitemError(Exception): 

1035 """ 

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

1037 

1038 Notes 

1039 ----- 

1040 This is an internal error. 

1041 """ 

1042 

1043 

1044class NoBufferPresent(Exception): 

1045 """ 

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

1047 """ 

1048 

1049 

1050class InvalidComparison(Exception): 

1051 """ 

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

1053 

1054 Notes 

1055 ----- 

1056 This is an internal error. 

1057 """ 

1058 

1059 

1060__all__ = [ 

1061 "AbstractMethodError", 

1062 "AttributeConflictWarning", 

1063 "CSSWarning", 

1064 "CategoricalConversionWarning", 

1065 "ChainedAssignmentError", 

1066 "ClosedFileError", 

1067 "DataError", 

1068 "DatabaseError", 

1069 "DtypeWarning", 

1070 "DuplicateLabelError", 

1071 "EmptyDataError", 

1072 "IncompatibilityWarning", 

1073 "IncompatibleFrequency", 

1074 "IndexingError", 

1075 "IntCastingNaNError", 

1076 "InvalidColumnName", 

1077 "InvalidComparison", 

1078 "InvalidIndexError", 

1079 "InvalidVersion", 

1080 "LossySetitemError", 

1081 "MergeError", 

1082 "NoBufferPresent", 

1083 "NullFrequencyError", 

1084 "NumExprClobberingError", 

1085 "NumbaUtilError", 

1086 "OptionError", 

1087 "OutOfBoundsDatetime", 

1088 "OutOfBoundsTimedelta", 

1089 "Pandas4Warning", 

1090 "Pandas5Warning", 

1091 "PandasChangeWarning", 

1092 "PandasDeprecationWarning", 

1093 "PandasFutureWarning", 

1094 "PandasPendingDeprecationWarning", 

1095 "ParserError", 

1096 "ParserWarning", 

1097 "PerformanceWarning", 

1098 "PossibleDataLossError", 

1099 "PossiblePrecisionLoss", 

1100 "PyperclipException", 

1101 "PyperclipWindowsException", 

1102 "SpecificationError", 

1103 "UndefinedVariableError", 

1104 "UnsortedIndexError", 

1105 "UnsupportedFunctionCall", 

1106 "ValueLabelTypeMismatch", 

1107]