Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pandas/core/flags.py: 44%
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
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
1from __future__ import annotations
3from typing import TYPE_CHECKING
4import weakref
6from pandas.util._decorators import set_module
8if TYPE_CHECKING:
9 from pandas.core.generic import NDFrame
12@set_module("pandas")
13class Flags:
14 """
15 Flags that apply to pandas objects.
17 “Flags” differ from “metadata”. Flags reflect properties of the pandas
18 object (the Series or DataFrame). Metadata refer to properties of the
19 dataset, and should be stored in DataFrame.attrs.
21 Parameters
22 ----------
23 obj : Series or DataFrame
24 The object these flags are associated with.
25 allows_duplicate_labels : bool, default True
26 Whether to allow duplicate labels in this object. By default,
27 duplicate labels are permitted. Setting this to ``False`` will
28 cause an :class:`errors.DuplicateLabelError` to be raised when
29 `index` (or columns for DataFrame) is not unique, or any
30 subsequent operation on introduces duplicates.
31 See :ref:`duplicates.disallow` for more.
33 .. warning::
35 This is an experimental feature. Currently, many methods fail to
36 propagate the ``allows_duplicate_labels`` value. In future versions
37 it is expected that every method taking or returning one or more
38 DataFrame or Series objects will propagate ``allows_duplicate_labels``.
40 See Also
41 --------
42 DataFrame.attrs : Dictionary of global attributes of this dataset.
43 Series.attrs : Dictionary of global attributes of this dataset.
45 Examples
46 --------
47 Attributes can be set in two ways:
49 >>> df = pd.DataFrame()
50 >>> df.flags
51 <Flags(allows_duplicate_labels=True)>
52 >>> df.flags.allows_duplicate_labels = False
53 >>> df.flags
54 <Flags(allows_duplicate_labels=False)>
56 >>> df.flags["allows_duplicate_labels"] = True
57 >>> df.flags
58 <Flags(allows_duplicate_labels=True)>
59 """
61 _keys: set[str] = {"allows_duplicate_labels"}
63 def __init__(self, obj: NDFrame, *, allows_duplicate_labels: bool) -> None:
64 self._allows_duplicate_labels = allows_duplicate_labels
65 self._obj = weakref.ref(obj)
67 @property
68 def allows_duplicate_labels(self) -> bool:
69 """
70 Whether this object allows duplicate labels.
72 Setting ``allows_duplicate_labels=False`` ensures that the
73 index (and columns of a DataFrame) are unique. Most methods
74 that accept and return a Series or DataFrame will propagate
75 the value of ``allows_duplicate_labels``.
77 See :ref:`duplicates` for more.
79 See Also
80 --------
81 DataFrame.attrs : Set global metadata on this object.
82 DataFrame.set_flags : Set global flags on this object.
84 Examples
85 --------
86 >>> df = pd.DataFrame({"A": [1, 2]}, index=["a", "a"])
87 >>> df.flags.allows_duplicate_labels
88 True
89 >>> df.flags.allows_duplicate_labels = False
90 Traceback (most recent call last):
91 ...
92 pandas.errors.DuplicateLabelError: Index has duplicates.
93 positions
94 label
95 a [0, 1]
96 """
97 return self._allows_duplicate_labels
99 @allows_duplicate_labels.setter
100 def allows_duplicate_labels(self, value: bool) -> None:
101 value = bool(value)
102 obj = self._obj()
103 if obj is None:
104 raise ValueError("This flag's object has been deleted.")
106 if not value:
107 for ax in obj.axes:
108 ax._maybe_check_unique()
110 self._allows_duplicate_labels = value
112 def __getitem__(self, key: str):
113 if key not in self._keys:
114 raise KeyError(key)
116 return getattr(self, key)
118 def __setitem__(self, key: str, value) -> None:
119 if key not in self._keys:
120 raise ValueError(f"Unknown flag {key}. Must be one of {self._keys}")
121 setattr(self, key, value)
123 def __repr__(self) -> str:
124 return f"<Flags(allows_duplicate_labels={self.allows_duplicate_labels})>"
126 def __eq__(self, other: object) -> bool:
127 if isinstance(other, type(self)):
128 return self.allows_duplicate_labels == other.allows_duplicate_labels
129 return False