10000 Optionally disallow duplicate labels by TomAugspurger · Pull Request #28394 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

Optionally disallow duplicate labels #28394

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 49 commits into from
Sep 3, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
090a758
ENH: Optionally disallow duplicate labels
TomAugspurger Jun 7, 2020
0962d19
fixup memory_usage test
TomAugspurger Jun 8, 2020
8e0089c
pickle
TomAugspurger Jun 8, 2020
6a2d568
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Jun 10, 2020
b9873db
lint
TomAugspurger Jun 10, 2020
d326ed5
doc
TomAugspurger Jun 10, 2020
fba3536
fixups
TomAugspurger Jun 10, 2020
7de8327
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Jun 17, 2020
f1e5932
handle concat
TomAugspurger Jun 17, 2020
c0f6390
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Jun 18, 2020
3dad6d5
handle mi
TomAugspurger Jun 18, 2020
e81327d
note on setting
TomAugspurger Jun 18, 2020
3254b8b
fixup
TomAugspurger Jun 18, 2020
04b6322
fix import, docs
TomAugspurger Jun 22, 2020
0c3db5b
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Jun 22, 2020
fdcdb31
handle insert
TomAugspurger Jun 22, 2020
cb7aeb3
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Jun 29, 2020
7d71326
wip inplace
TomAugspurger Jun 29, 2020
c0a6105
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Jun 30, 2020
3fa067d
tests for inplace duplicates
TomAugspurger Jun 30, 2020
91ca7a1
move to generic
TomAugspurger Jun 30, 2020
097dd1c
fixup
TomAugspurger Jun 30, 2020
8248634
add note
TomAugspurger Jun 30, 2020
df42b44
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Aug 5, 2020
aff9303
update
TomAugspurger Aug 5, 2020
64334ca
update
TomAugspurger Aug 5, 2020
bef80bd
update
TomAugspurger Aug 5, 2020
7d09c8b
fixup docs
TomAugspurger Aug 5, 2020
674cb97
typing
TomAugspurger Aug 5, 2020
cc80b02
fixed typo
TomAugspurger Aug 6, 2020
c9030f1
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Aug 7, 2020
457683c
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Aug 20, 2020
4ced351
todo
TomAugspurger Aug 21, 2020
f5bb12c
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Aug 24, 2020
4f7c350
flags
TomAugspurger Aug 24, 2020
ecb97d5
rm _flags
TomAugspurger Aug 24, 2020
d1a81fb
fixups
TomAugspurger Aug 24, 2020
74a4eb8
lint
TomAugspurger Aug 24, 2020
50042e1
lint
TomAugspurger Aug 25, 2020
6a1560f
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Aug 26, 2020
f61118d
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Aug 27, 2020
a336027
Pickle
TomAugspurger Aug 27, 2020
60c853c
Doc
TomAugspurger Aug 27, 2020
cb5d4f2
test flags
TomAugspurger Aug 27, 2020
98af7b5
pickle
TomAugspurger Aug 28, 2020
3a50741
remove debug
TomAugspurger Aug 28, 2020
675e49d
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Aug 31, 2020
e88f7e2
Merge remote-tracking branch 'upstream/master' into unique-index
TomAugspurger Sep 1, 2020
bf23fda
fixups
TomAugspurger Sep 1, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
flags
  • Loading branch information
TomAugspurger committed Aug 24, 2020
commit 4f7c350d9bda6b36ee476a4771f86e855a28d091
16 changes: 15 additions & 1 deletion doc/source/reference/frame.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ Attributes and underlying data
DataFrame.shape
DataFrame.memory_usage
DataFrame.empty
DataFrame.allows_duplicate_labels
DataFrame.set_flags

Conversion
Expand Down Expand Up @@ -278,6 +277,21 @@ Time Series-related
DataFrame.tz_convert
DataFrame.tz_localize

.. _api.frame.flags:

Flags
~~~~~

Flags refer to attributes of the pandas object. Properties of the dataset (like
the date is was recorded, the URL it was accessed from, etc.) should be stored
in :attr:`DataFrame.attrs`.

.. autosummary::
:toctree: api/

Flags


.. _api.frame.metadata:

Metadata
Expand Down
15 changes: 14 additions & 1 deletion doc/source/reference/series.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Attributes
Series.empty
Series.dtypes
Series.name
Series.allows_duplicate_labels
Series.flags
Series.set_flags

Conversion
Expand Down Expand Up @@ -529,6 +529,19 @@ Sparse-dtype specific methods and attributes are provided under the
Series.sparse.from_coo
Series.sparse.to_coo

.. _api.series.flags:

Flags
~~~~~

Flags refer to attributes of the pandas object. Properties of the dataset (like
the date is was recorded, the URL it was accessed from, etc.) should be stored
in :attr:`Series.attrs`.

.. autosummary::
:toctree: api/

Flags

.. _api.series.metadata:

Expand Down
30 changes: 17 additions & 13 deletions doc/source/user_guide/duplicates.rst
Original file line number Diff line number Diff line change
Expand Up @@ -121,42 +121,46 @@ an exception will be raised.
.. ipython:: python
:okexcept:

pd.Series([0, 1, 2], index=['a', 'b', 'b'], allows_duplicate_labels=False)
pd.Series([0, 1, 2], index=['a', 'b', 'b']).set_flags(allows_duplicate_labels=False)

This applies to both row and column labels for a :class:`DataFrame`

.. ipython:: python
:okexcept:

pd.DataFrame([[0, 1, 2], [3, 4, 5]], columns=["A", "B", "C"],
allows_duplicate_labels=False)
pd.DataFrame(
[[0, 1, 2], [3, 4, 5]], columns=["A", "B", "C"],
).set_flags(allows_duplicate_labels=False)

This attribute can be checked or set with :attr:`~DataFrame.allows_duplicate_labels`,
This attribute can be checked or set with :attr:`~DataFrame.flags.allows_duplicate_labels`,
which indicates whether that object can have duplicate labels.

.. ipython:: python

df = pd.DataFrame({"A": [0, 1, 2, 3]},
index=['x', 'y', 'X', 'Y'],
allows_duplicate_labels=False)
df = (
pd.DataFrame({"A": [0, 1, 2, 3]},
index=['x', 'y', 'X', 'Y'])
.set_flags(allows_duplicate_labels=False)
)
df
df.allows_duplicate_labels
df.flags.allows_duplicate_labels

:meth:`DataFrame.set_flags` can be used to return a new ``DataFrame`` with attributes
like ``allows_duplicate_labels`` set to some value

.. ipython:: python

df2 = df.set_flags(allows_duplicate_labels=True)
df2.allows_duplicate_labels
df2.flags.allows_duplicate_labels

The new ``DataFrame`` returned is a view on the same data as the old ``DataFrame``.
Or the property can just be set directly on the same object


.. ipython:: python

df2.allows_duplicate_labels = False
df2.allows_duplicate_labels
df2.flags.allows_duplicate_labels = False
df2.flags.allows_duplicate_labels

When processing raw, messy data you might initially read in the messy data
(which potentially has duplicate labels), deduplicate, and then disallow duplicates
Expand All @@ -167,7 +171,7 @@ going forward, to ensure that your data pipeline doesn't introduce duplicates.

>>> raw = pd.read_csv("...")
>>> deduplicated = raw.groupby(level=0).first() # remove duplicates
>>> deduplicated.allows_duplicate_labels = False # disallow going forward
>>> deduplicated.flags.allows_duplicate_labels = False # disallow going forward

Setting ``allows_duplicate_labels=True`` on a ``Series`` or ``DataFrame`` with duplicate
labels or performing an operation that introduces duplicate labels on a ``Series`` or
Expand All @@ -191,7 +195,7 @@ operations.
.. ipython:: python
:okexcept:

s1 = pd.Series(0, index=['a', 'b'], allows_duplicate_labels=False)
s1 = pd.Series(0, index=['a', 'b']).set_flags(allows_duplicate_labels=False)
s1
s1.head().rename({"a": "b"})

Expand Down
9 changes: 7 additions & 2 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,14 @@ By default, duplicates continue to be allowed
.. ipython:: python
:okexcept:

pd.Series([1, 2], index=['a', 'a'], allows_duplicate_labels=False)
pd.Series([1, 2], index=['a', 'a']).set_flags(allows_duplicate_labels=False)

Pandas will propagate the ``allows_duplicate_labels`` property through many operations.

.. ipython:: python
:okexcept:

a = pd.Series([1, 2], index=['a', 'b'], allows_duplicate_labels=False)
a = pd.Series([1, 2], index=['a', 'b']).set_flags(allows_duplicate_labels=False)
a
# An operation introducing duplicates
a.reindex(['a', 'b', 'a'])
Expand All @@ -52,6 +52,11 @@ Pandas will propagate the ``allows_duplicate_labels`` property through many oper

See :ref:`duplicates` for more.

The ``allows_duplicate_labels`` flag is stored in the new :attr:`DataFrame.flags`
attribute. This stores global attributes that apply to the *pandas object*. This
differs from :attr:`DataFrame.attrs`, which stores information that applies to
the dataset.

Passing arguments to fsspec backends
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Expand Down
1 change: 1 addition & 0 deletions pandas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
to_datetime,
to_timedelta,
# misc
Flags,
Grouper,
factorize,
unique,
Expand Down
18 changes: 16 additions & 2 deletions pandas/core/_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,26 @@ class Flags:
"""
Flags that apply to pandas objects.

.. versionadded:: 1.2.0

Parameters
----------
obj : Series or DataFrame
The object these flags are associated with
allows_duplicate_labels : bool
Whether the object allows duplicate labels
allows_duplicate_labels : bool, default True
Whether to allow duplicate labels in this object. By default,
duplicate labels are permitted. Setting this to ``False`` will
cause an :class:`errors.DuplicateLabelError` to be raised when
`index` (or columns for DataFrame) is not unique, or any
subsequent operation on introduces duplicates.
See :ref:`duplicates.disallow` for more.

.. warning::

This is an experimental feature. Currently, many methods fail to
propagate the ``allows_duplicate_labels`` value. In future versions
it is expected that every method taking or returning one or more
DataFrame or Series objects will propagate ``allows_duplicate_labels``.

Notes
-----
Expand Down
1 change: 1 addition & 0 deletions pandas/core/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
)
from pandas.core.arrays.string_ import StringDtype
from pandas.core.construction import array
from pandas.core.flags import Flags
from pandas.core.groupby import Grouper, NamedAgg
from pandas.core.indexes.api import (
CategoricalIndex,
Expand Down
99 changes: 99 additions & 0 deletions pandas/core/flags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import weakref


class Flags:
"""
Flags that apply to pandas objects.

Parameters
----------
obj : Series or DataFrame
The object these flags are associated with
allows_duplicate_labels : bool
Whether the object allows duplicate labels

Notes
-----
Attributes can be set in two ways

>>> df = pd.DataFrame()
>>> df.flags
<Flags(allows_duplicate_labels=True)>
>>> df.flags.allows_duplicate_labels = False
>>> df.flags
<Flags(allows_duplicate_labels=False)>

>>> df.flags['allows_duplicate_labels'] = True
>>> df.flags
<Flags(allows_duplicate_labels=True)>
"""

_keys = {"allows_duplicate_labels"}

def __init__(self, obj, *, allows_duplicate_labels):
self._allows_duplicate_labels = allows_duplicate_labels
self._obj = weakref.ref(obj)

@property
def allows_duplicate_labels(self) -> bool:
"""
Whether this object allows duplicate labels.

Setting ``allows_duplicate_labels=False`` ensures that the
index (and columns of a DataFrame) are unique. Most methods
that accept and return a Series or DataFrame will propagate
the value of ``allows_duplicate_labels``.

See :ref:`duplicates` for more.

See Also
--------
DataFrame.attrs : Set global metadata on this object.
DataFrame.set_flags : Set global flags on this object.

Examples
--------
>>> df = pd.DataFrame({"A": [1, 2]}, index=['a', 'a'])
>>> df.allows_duplicate_labels
True
>>> df.allows_duplicate_labels = False
Traceback (most recent call last):
...
pandas.errors.DuplicateLabelError: Index has duplicates.
positions
label
a [0, 1]
"""
return self._allows_duplicate_labels

@allows_duplicate_labels.setter
def allows_duplicate_labels(self, value: bool):
value = bool(value)
obj = self._obj()
if obj is None:
raise ValueError("This flags object has been deleted.")

if not value:
for ax in obj.axes:
ax._maybe_check_unique()

self._allows_duplicate_labels = value

def __getitem__(self, key):
if key not in self._keys:
raise KeyError(key)

return getattr(self, key)

def __setitem__(self, key, value):
if key not in self._keys:
raise ValueError(f"Unknown flag {key}. Must be one of {self._keys}")
setattr(self, key, value)

def __repr__(self):
return f"<Flags(allows_duplicate_labels={self.allows_duplicate_labels})>"

def __eq__(self, other):
if isinstance(other, type(self)):
return self.allows_duplicate_labels == other.allows_duplicate_labels
return False
16 changes: 0 additions & 16 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,22 +369,6 @@ class DataFrame(NDFrame):
Data type to force. Only a single dtype is allowed. If None, infer.
copy : bool, default False
Copy data from inputs. Only affects DataFrame / 2d ndarray input.
allows_duplicate_labels : bool, default True
Whether to allow duplicate row or column labels in this DataFrame.
By default, duplicate labels are permitted. Setting this to ``False``
will cause an :class:`errors.DuplicateLabelError` to be raised when
`index` or `columns` are not unique, or when any subsequent operation
on this DataFrame introduces duplicates. See :ref:`duplicates.disallow`
for more.

.. versionadded:: 1.1.0

.. warning::

This is an experimental feature. Currently, many methods fail to
propagate the ``allows_duplicate_labels`` value. In future versions
it is expected that every method taking or returning one or more
DataFrame or Series objects will propagate ``allows_duplicate_labels``.

See Also
--------
Expand Down
Loading
0