flags.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. from __future__ import annotations
  2. import weakref
  3. class Flags:
  4. """
  5. Flags that apply to pandas objects.
  6. .. versionadded:: 1.2.0
  7. Parameters
  8. ----------
  9. obj : Series or DataFrame
  10. The object these flags are associated with.
  11. allows_duplicate_labels : bool, default True
  12. Whether to allow duplicate labels in this object. By default,
  13. duplicate labels are permitted. Setting this to ``False`` will
  14. cause an :class:`errors.DuplicateLabelError` to be raised when
  15. `index` (or columns for DataFrame) is not unique, or any
  16. subsequent operation on introduces duplicates.
  17. See :ref:`duplicates.disallow` for more.
  18. .. warning::
  19. This is an experimental feature. Currently, many methods fail to
  20. propagate the ``allows_duplicate_labels`` value. In future versions
  21. it is expected that every method taking or returning one or more
  22. DataFrame or Series objects will propagate ``allows_duplicate_labels``.
  23. Notes
  24. -----
  25. Attributes can be set in two ways
  26. >>> df = pd.DataFrame()
  27. >>> df.flags
  28. <Flags(allows_duplicate_labels=True)>
  29. >>> df.flags.allows_duplicate_labels = False
  30. >>> df.flags
  31. <Flags(allows_duplicate_labels=False)>
  32. >>> df.flags['allows_duplicate_labels'] = True
  33. >>> df.flags
  34. <Flags(allows_duplicate_labels=True)>
  35. """
  36. _keys = {"allows_duplicate_labels"}
  37. def __init__(self, obj, *, allows_duplicate_labels) -> None:
  38. self._allows_duplicate_labels = allows_duplicate_labels
  39. self._obj = weakref.ref(obj)
  40. @property
  41. def allows_duplicate_labels(self) -> bool:
  42. """
  43. Whether this object allows duplicate labels.
  44. Setting ``allows_duplicate_labels=False`` ensures that the
  45. index (and columns of a DataFrame) are unique. Most methods
  46. that accept and return a Series or DataFrame will propagate
  47. the value of ``allows_duplicate_labels``.
  48. See :ref:`duplicates` for more.
  49. See Also
  50. --------
  51. DataFrame.attrs : Set global metadata on this object.
  52. DataFrame.set_flags : Set global flags on this object.
  53. Examples
  54. --------
  55. >>> df = pd.DataFrame({"A": [1, 2]}, index=['a', 'a'])
  56. >>> df.flags.allows_duplicate_labels
  57. True
  58. >>> df.flags.allows_duplicate_labels = False
  59. Traceback (most recent call last):
  60. ...
  61. pandas.errors.DuplicateLabelError: Index has duplicates.
  62. positions
  63. label
  64. a [0, 1]
  65. """
  66. return self._allows_duplicate_labels
  67. @allows_duplicate_labels.setter
  68. def allows_duplicate_labels(self, value: bool) -> None:
  69. value = bool(value)
  70. obj = self._obj()
  71. if obj is None:
  72. raise ValueError("This flag's object has been deleted.")
  73. if not value:
  74. for ax in obj.axes:
  75. ax._maybe_check_unique()
  76. self._allows_duplicate_labels = value
  77. def __getitem__(self, key):
  78. if key not in self._keys:
  79. raise KeyError(key)
  80. return getattr(self, key)
  81. def __setitem__(self, key, value) -> None:
  82. if key not in self._keys:
  83. raise ValueError(f"Unknown flag {key}. Must be one of {self._keys}")
  84. setattr(self, key, value)
  85. def __repr__(self) -> str:
  86. return f"<Flags(allows_duplicate_labels={self.allows_duplicate_labels})>"
  87. def __eq__(self, other):
  88. if isinstance(other, type(self)):
  89. return self.allows_duplicate_labels == other.allows_duplicate_labels
  90. return False