Index objects are not required to be unique; you can have duplicate row
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.
In [1]: importpandasaspdIn [2]: importnumpyasnp
Consequences of Duplicate Labels
Some pandas methods (Series.reindex() for example) just don’t work with
duplicates present. The output can’t be determined, and so pandas raises.
In [3]: s1=pd.Series([0,1,2],index=["a","b","b"])In [4]: s1.reindex(["a","b","c"])---------------------------------------------------------------------------ValueErrorTraceback (most recent call last)
CellIn[4],line1----> 1s1.reindex(["a","b","c"])File ~/work/pandas/pandas/pandas/core/series.py:5172, in Series.reindex(self, index, axis, method, copy, level, fill_value, limit, tolerance)5155@doc(5156NDFrame.reindex,# type: ignore[has-type]5157klass=_shared_doc_kwargs["klass"],(...)5170tolerance=None,5171)->Series:-> 5172returnsuper().reindex(5173index=index,5174method=method,5175copy=copy,5176level=level,5177fill_value=fill_value,5178limit=limit,5179tolerance=tolerance,5180)File ~/work/pandas/pandas/pandas/core/generic.py:5632, in NDFrame.reindex(self, labels, index, columns, axis, method, copy, level, fill_value, limit, tolerance)5629returnself._reindex_multi(axes,copy,fill_value)5631# perform the reindex on the axes-> 5632returnself._reindex_axes(5633axes,level,limit,tolerance,method,fill_value,copy5634).__finalize__(self,method="reindex")File ~/work/pandas/pandas/pandas/core/generic.py:5655, in NDFrame._reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy)5652continue5654ax=self._get_axis(a)-> 5655new_index,indexer=ax.reindex(5656labels,level=level,limit=limit,tolerance=tolerance,method=method5657)5659axis=self._get_axis_number(a)5660obj=obj._reindex_with_indexers(5661{axis:[new_index,indexer]},5662fill_value=fill_value,5663copy=copy,5664allow_dups=False,5665)File ~/work/pandas/pandas/pandas/core/indexes/base.py:4436, in Index.reindex(self, target, method, level, limit, tolerance)4433raiseValueError("cannot handle a non-unique multi-index!")4434elifnotself.is_unique:4435# GH#42568-> 4436raiseValueError("cannot reindex on an axis with duplicate labels")4437else:4438indexer,_=self.get_indexer_non_unique(target)ValueError: cannot reindex on an axis with duplicate labels
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.
In [5]: df1=pd.DataFrame([[0,1,2],[3,4,5]],columns=["A","A","B"])In [6]: df1Out[6]: A A B0 0 1 21 3 4 5
We have duplicates in the columns. If we slice 'B', we get back a Series
In [7]: df1["B"]# a seriesOut[7]: 0 21 5Name: B, dtype: int64
But slicing 'A' returns a DataFrame
In [8]: df1["A"]# a DataFrameOut[8]: A A0 0 11 3 4
This applies to row labels as well
In [9]: df2=pd.DataFrame({"A":[0,1,2]},index=["a","a","b"])In [10]: df2Out[10]: Aa 0a 1b 2In [11]: df2.loc[
Duplicate Label Detection
You can check whether an Index (storing the row or column labels) is
unique with Index.is_unique:
In [13]: df2Out[13]: Aa 0a 1b 2In [14]: df2.index.is_uniqueOut[14]: FalseIn [15]: df2.columns.is_uniqueOut[15]: True
Index.duplicated() will return a boolean ndarray indicating whether a
label is repeated.
In [16]: df2.index.duplicated()Out[16]: array([False, True, False])
Which can be used as a boolean filter to drop duplicate rows.
In [17]: df2.loc[~df2.index.duplicated(),:]Out[17]: Aa 0b 2
If you need additional logic to handle duplicate labels, rather than just
dropping the repeats, using 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.
In [18]: df2.groupby(level=0).mean()Out[18]: Aa 0.5b 2.0
Disallowing Duplicate Labels
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 pandas.concat(),
rename(), etc.). Both Series and DataFramedisallow duplicate labels by calling .set_flags(allows_duplicate_labels=False).
(the default is to allow them). If there are duplicate labels, an exception
will be raised.
In [19]: pd.Series([0,1,2],index=["a","b","b"]).set_flags(allows_duplicate_labels=False)---------------------------------------------------------------------------DuplicateLabelErrorTraceback (most recent call last)
CellIn[19],line1----> 1pd.Series
in
in
in
in
: Index has duplicates.
This applies to both row and column labels for a DataFrame
In [20]: 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 allows_duplicate_labels,
which indicates whether that object can have duplicate labels.
In [21]: df=pd.DataFrame({"A":[0,1,2,3]},index=["x","y","X","Y"]).set_flags( ....: allows_duplicate_labels=False ....:
DataFrame.set_flags() can be used to return a new DataFrame with attributes
like allows_duplicate_labels set to some value
In [24]: df2=df.set_flags(allows_duplicate_labels=True)In [25]: df2.flags.allows_duplicate_labelsOut[25]: True
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
In [26]: df2.flags.allows_duplicate_labels=FalseIn [27]: df2.flags.allows_duplicate_labelsOut[27]: False
When processing raw, messy data you might initially read in the messy data
(which potentially has duplicate labels), deduplicate, and then disallow duplicates
going forward, to ensure that your data pipeline doesn’t introduce duplicates.
Setting allows_duplicate_labels=False on a Series or DataFrame with duplicate
labels or performing an operation that introduces duplicate labels on a Series or
DataFrame that disallows duplicates will raise an
errors.DuplicateLabelError.
In [28]: df.rename(str.upper)---------------------------------------------------------------------------DuplicateLabelErrorTraceback (most recent call last)
CellIn[28],line1----> 1df.rename(str.upper)File ~/work/pandas/pandas/pandas/core/frame.py:5789, in DataFrame.rename(self, mapper, index, columns, axis, copy, inplace, level, errors)5658def
in
in
in
in
: Index has duplicates.
This error message contains the labels that are duplicated, and the numeric positions
of all the duplicates (including the “original”) in the Series or DataFrame
Duplicate Label Propagation
In general, disallowing duplicates is “sticky”. It’s preserved through
operations.
In [29]: s1=pd.Series(0,index=["a","b"]).set_flags(allows_duplicate_labels=False)In [30]: s1Out[30]: a 0b 0dtype: int64In [31]: s1
Traceback (most recent call last)
in
in
in
in
in
: Index has duplicates.