Skip to content
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

Optionally disallow duplicate labels #28394

Merged
merged 49 commits into from
Sep 3, 2020
Merged
Show file tree
Hide file tree
Changes from 9 commits
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
172 changes: 172 additions & 0 deletions doc/source/user_guide/duplicates.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
.. _duplicates:

****************
Duplicate Labels
****************

:class:`Index` objects are not required to be unique; you can have duplicate row
TomAugspurger marked this conversation as resolved.
Show resolved Hide resolved
or column labels. This may be a bit confusing at first. If you're familiar with
SQL, you know that row labels are similar to a primary key on a table, and you
would never want duplicates in a SQL table. But one of pandas' roles is to clean
messy, real-world data before it goes to some downstream system. And real-world
data has duplicates, even in fields that are supposed to be unique.

This section describes how duplicate labels change the behavior of certain
operations, and how prevent duplicates from arising during operations, or to
detect them if they do.

.. ipython:: python

import pandas as pd
import numpy as np
TomAugspurger marked this conversation as resolved.
Show resolved Hide resolved

Consequences of Duplicate Labels
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Some pandas methods (:meth:`Series.reindex` for example) just don't work with
duplicates present. The output can't be determined, and so pandas raises.

.. ipython:: python
:okexcept:

s1 = pd.Series([0, 1, 2], index=['a', 'b', 'b'])
s1.reindex(['a', 'b', 'c'])

Other methods, like indexing, can give very surprising results. Typically
indexing with a scalar will *reduce dimensionality*. Slicing a ``DataFrame``
with a scalar will return a ``Series``. Slicing a ``Series`` with a scalar will
return a scalar. But with duplicates, this isn't the case.

.. ipython:: python

df1 = pd.DataFrame([[0, 1, 2], [3, 4, 5]], columns=['A', 'A', 'B'])
df1

We have duplicates in the columns. If we slice ``'B'``, we get back a ``Series``

.. ipython:: python

df1['B'] # a series

But slicing ``'A'`` returns a ``DataFrame``


.. ipython:: python

df1['A'] # a DataFrame

This applies to row labels as well

.. ipython:: python

df2 = pd.DataFrame({"A": [0, 1, 2]}, index=['a', 'a', 'b'])
df2
df2.loc['b', 'A'] # a scalar
df2.loc['a', 'A'] # a Series

Duplicate Label Detection
~~~~~~~~~~~~~~~~~~~~~~~~~

You can check whether an :class:`Index` (storing the row or column labels) is
unique with :attr:`Index.is_unique`:

.. ipython:: python

df2
df2.index.is_unique
df2.columns.is_unique

.. note::

Checking whether an index is unique is somewhat expensive for large datasets.
Pandas does cache this result, so re-checking on the same index is very fast.

:meth:`Index.duplicated` will return a boolean ndarray indicating whether a
label is a repeat.
TomAugspurger marked this conversation as resolved.
Show resolved Hide resolved

.. ipython:: python

df2.index.duplicated()

Which can be used as a boolean filter to drop duplicate rows.

.. ipython:: python

df2.loc[~df2.index.duplicated(), :]

If you need additional logic to handle duplicate labels, rather than just
dropping the repeats, using :meth:`~DataFrame.groupby` on the index is a common
trick. For example, we'll resolve duplicates by taking the average of all rows
with the same label.

.. ipython:: python

df2.groupby(level=0).mean()

.. _duplicates.disallow:

Disallowing Duplicate Labels
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. versionadded:: 1.1.0
TomAugspurger marked this conversation as resolved.
Show resolved Hide resolved

As noted above, handling duplicates is an important feature when reading in raw
data. That said, you may want to avoid introducing duplicates as part of a data
processing pipeline (from methods like :meth:`pandas.concat`,
:meth:`~DataFrame.rename`, etc.). Both :class:`Series` and :class:`DataFrame`
can be created with the argument ``allows_duplicate_labels=False`` to *disallow*
TomAugspurger marked this conversation as resolved.
Show resolved Hide resolved
duplicate labels (the default is to allow them). If there are duplicate labels,
an exception will be raised.

.. ipython:: python
:okexcept:

pd.Series([0, 1, 2], index=['a', 'b', 'b'], 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)

This attribute can be checked or set with :attr:`~DataFrame.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
df.allows_duplicate_labels

Performing an operation that introduces duplicate labels on a ``Series`` or
``DataFrame`` that disallows duplicates will raise an
:class:`errors.DuplicateLabelError`.

.. ipython:: python
:okexcept:

df.rename(str.upper)

Duplicate Label Propagation
^^^^^^^^^^^^^^^^^^^^^^^^^^^

In general, disallowing duplicates is "sticky". It's preserved through
operations.

.. ipython:: python
:okexcept:

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

.. 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``.
jreback marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions doc/source/user_guide/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Further information on any specific method can be obtained in the
reshaping
text
missing_data
duplicates
jreback marked this conversation as resolved.
Show resolved Hide resolved
categorical
integer_na
boolean
Expand Down
39 changes: 39 additions & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,45 @@ For example:
pd.to_datetime(tz_strs, format='%Y-%m-%d %H:%M:%S %z', utc=True)
pd.to_datetime(tz_strs, format='%Y-%m-%d %H:%M:%S %z')

.. _whatsnew_110.duplicate_labels:

Optionally disallow duplicate labels
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

:class:`Series` and :class:`DataFrame` can now be created with ``allows_duplicate_labels=False`` flag to
control whether the index or columns can contain duplicate labels. This can be used to prevent accidental
introduction of duplicate labels, which can affect downstream operations.

By default, duplicates continue to be allowed

.. ipython:: python

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

.. ipython:: python
:okexcept:

pd.Series([1, 2], index=['a', 'a'], 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
# An operation introducing duplicates
a.reindex(['a', 'b', 'a'])

.. 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 :ref:`duplicates` for more.

.. _whatsnew_110.grouper_resample_origin:

Grouper and resample now supports the arguments origin and offset
Expand Down
23 changes: 21 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,22 @@ 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 Expand Up @@ -436,6 +452,7 @@ def __init__(
columns: Optional[Axes] = None,
dtype: Optional[Dtype] = None,
copy: bool = False,
allows_duplicate_labels=True,
):
if data is None:
data = {}
Expand All @@ -448,7 +465,9 @@ def __init__(
if isinstance(data, BlockManager):
if index is None and columns is None and dtype is None and copy is False:
# GH#33357 fastpath
NDFrame.__init__(self, data)
NDFrame.__init__(
self, data, allows_duplicate_labels=allows_duplicate_labels
)
return

mgr = self._init_mgr(
Expand Down Expand Up @@ -534,7 +553,7 @@ def __init__(
else:
raise ValueError("DataFrame constructor not properly called!")

NDFrame.__init__(self, mgr)
NDFrame.__init__(self, mgr, allows_duplicate_labels=allows_duplicate_labels)

# ----------------------------------------------------------------------

Expand Down
30 changes: 30 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ def __init__(
self,
data: BlockManager,
copy: bool = False,
allows_duplicate_labels: bool = True,
attrs: Optional[Mapping[Optional[Hashable], Any]] = None,
):
# copy kwarg is retained for mypy compat, is not used
Expand All @@ -208,6 +209,7 @@ def __init__(
else:
attrs = dict(attrs)
object.__setattr__(self, "_attrs", attrs)
object.__setattr__(self, "allows_duplicate_labels", allows_duplicate_labels)

@classmethod
def _init_mgr(cls, mgr, axes, dtype=None, copy: bool = False) -> BlockManager:
Expand Down Expand Up @@ -246,6 +248,23 @@ def attrs(self) -> Dict[Optional[Hashable], Any]:
def attrs(self, value: Mapping[Optional[Hashable], Any]) -> None:
self._attrs = dict(value)

@property
def allows_duplicate_labels(self) -> bool:
WillAyd marked this conversation as resolved.
Show resolved Hide resolved
"""
Whether this object allows duplicate labels.
"""
return self._allows_duplicate_labels

@allows_duplicate_labels.setter
def allows_duplicate_labels(self, value: bool):
value = bool(value)
if not value:
for ax in self.axes:
ax._maybe_check_unique()

# avoid `can_hold_identifiers` check.
object.__setattr__(self, "_allows_duplicate_labels", value)

@classmethod
def _validate_dtype(cls, dtype):
""" validate the passed dtype """
Expand Down Expand Up @@ -1841,6 +1860,10 @@ def __setstate__(self, state):
if typ is not None:
attrs = state.get("_attrs", {})
object.__setattr__(self, "_attrs", attrs)
allows_duplicate_labels = state.get("_allows_duplicate_labels", True)
object.__setattr__(
self, "_allows_duplicate_labels", allows_duplicate_labels
)

# set in the order of internal names
# to avoid definitional recursion
Expand Down Expand Up @@ -5205,10 +5228,17 @@ def __finalize__(
if isinstance(other, NDFrame):
for name in other.attrs:
self.attrs[name] = other.attrs[name]

self.allows_duplicate_labels = other.allows_duplicate_labels
# For subclasses using _metadata.
for name in self._metadata:
assert isinstance(name, str)
object.__setattr__(self, name, getattr(other, name, None))

if method == "concat":
allows_duplicate_labels = all(x.allows_duplicate_labels for x in other.objs)
self.allows_duplicate_labels = allows_duplicate_labels

return self

def __getattr__(self, name: str):
Expand Down
20 changes: 20 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,26 @@ def _simple_new(cls, values, name: Label = None):
def _constructor(self):
return type(self)

def _maybe_check_unique(self):
jreback marked this conversation as resolved.
Show resolved Hide resolved
from pandas.errors import DuplicateLabelError
TomAugspurger marked this conversation as resolved.
Show resolved Hide resolved

if not self.is_unique:
# TODO: position, value, not too large.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah maybe an arg to show the first 10 duplicates

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's truncated, following our usual repr's settings. I'll remove the todo

In [3]: s = pd.Series(1, index=[0] * 200).set_flags(allows_duplicate_labels=False)
---------------------------------------------------------------------------
DuplicateLabelError                       Traceback (most recent call last)
<ipython-input-3-ece63ed32110> in <module>
----> 1 s = pd.Series(1, index=[0] * 200).set_flags(allows_duplicate_labels=False)

~/sandbox/pandas/pandas/core/generic.py in set_flags(self, copy, allows_duplicate_labels)
    349         df = self.copy(deep=copy)
    350         if allows_duplicate_labels is not None:
--> 351             df.flags["allows_duplicate_labels"] = allows_duplicate_labels
    352         return df
    353

~/sandbox/pandas/pandas/core/flags.py in __setitem__(self, key, value)
    103         if key not in self._keys:
    104             raise ValueError(f"Unknown flag {key}. Must be one of {self._keys}")
--> 105         setattr(self, key, value)
    106
    107     def __repr__(self):

~/sandbox/pandas/pandas/core/flags.py in allows_duplicate_labels(self, value)
     90         if not value:
     91             for ax in obj.axes:
---> 92                 ax._maybe_check_unique()
     93
     94         self._allows_duplicate_labels = value

~/sandbox/pandas/pandas/core/indexes/base.py in _maybe_check_unique(self)
    491             msg += "\n{}".format(duplicates)
    492
--> 493             raise DuplicateLabelError(msg)
    494
    495     def _format_duplicate_message(self):

DuplicateLabelError: Index has duplicates.
                                               positions
label
0      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
In [10]: s = pd.Series(1, index=np.arange(100).repeat(10)).set_flags(allows_duplicate_labels=False)
---------------------------------------------------------------------------
DuplicateLabelError                       Traceback (most recent call last)
<ipython-input-10-452fca37a730> in <module>
----> 1 s = pd.Series(1, index=np.arange(100).repeat(10)).set_flags(allows_duplicate_labels=False)

~/sandbox/pandas/pandas/core/generic.py in set_flags(self, copy, allows_duplicate_labels)
    349         df = self.copy(deep=copy)
    350         if allows_duplicate_labels is not None:
--> 351             df.flags["allows_duplicate_labels"] = allows_duplicate_labels
    352         return df
    353

~/sandbox/pandas/pandas/core/flags.py in __setitem__(self, key, value)
    103         if key not in self._keys:
    104             raise ValueError(f"Unknown flag {key}. Must be one of {self._keys}")
--> 105         setattr(self, key, value)
    106
    107     def __repr__(self):

~/sandbox/pandas/pandas/core/flags.py in allows_duplicate_labels(self, value)
     90         if not value:
     91             for ax in obj.axes:
---> 92                 ax._maybe_check_unique()
     93
     94         self._allows_duplicate_labels = value

~/sandbox/pandas/pandas/core/indexes/base.py in _maybe_check_unique(self)
    491             msg += "\n{}".format(duplicates)
    492
--> 493             raise DuplicateLabelError(msg)
    494
    495     def _format_duplicate_message(self):

DuplicateLabelError: Index has duplicates.
                                               positions
label
0                         [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1               [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
2               [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
3               [30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
4               [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
...                                                  ...
95     [950, 951, 952, 953, 954, 955, 956, 957, 958, ...
96     [960, 961, 962, 963, 964, 965, 966, 967, 968, ...
97     [970, 971, 972, 973, 974, 975, 976, 977, 978, ...
98     [980, 981, 982, 983, 984, 985, 986, 987, 988, ...
99     [990, 991, 992, 993, 994, 995, 996, 997, 998, ...

[100 rows x 1 columns]

msg = """Index has duplicates."""
duplicates = self._format_duplicate_message()
jreback marked this conversation as resolved.
Show resolved Hide resolved
msg += "\n{}".format(duplicates)

raise DuplicateLabelError(msg)

def _format_duplicate_message(self):
from pandas import Series

duplicates = self[self.duplicated(keep="first")].unique()
jreback marked this conversation as resolved.
Show resolved Hide resolved
assert len(duplicates)

out = Series(np.arange(len(self))).groupby(self).agg(list)[duplicates]
return out.rename_axis("label").to_frame(name="positions")

# --------------------------------------------------------------------
# Index Internals Methods

Expand Down
Loading