重复标签#
Index
对象不要求是唯一的;你可以有重复的行或列标签。这最初可能有点令人困惑。如果你熟悉 SQL,你会知道行标签类似于表中的主键,并且你绝不希望 SQL 表中出现重复项。但是 pandas 的作用之一是在数据进入下游系统之前,清理杂乱的真实世界数据。而真实世界的数据确实存在重复项,即使在那些本应是唯一值的字段中也是如此。
本节描述了重复标签如何改变某些操作的行为,以及如何防止操作过程中出现重复项,或者如何在出现重复项时检测它们。
In [1]: import pandas as pd
In [2]: import numpy as np
重复标签的后果#
某些 pandas 方法(例如 Series.reindex()
)在存在重复项时无法工作。此时输出无法确定,因此 pandas 会引发错误。
In [3]: s1 = pd.Series([0, 1, 2], index=["a", "b", "b"])
In [4]: s1.reindex(["a", "b", "c"])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[4], line 1
----> 1 s1.reindex(["a", "b", "c"])
File ~/work/pandas/pandas/pandas/core/series.py:5164, in Series.reindex(self, index, axis, method, copy, level, fill_value, limit, tolerance)
5147 @doc(
5148 NDFrame.reindex, # type: ignore[has-type]
5149 klass=_shared_doc_kwargs["klass"],
(...)
5162 tolerance=None,
5163 ) -> Series:
-> 5164 return super().reindex(
5165 index=index,
5166 method=method,
5167 copy=copy,
5168 level=level,
5169 fill_value=fill_value,
5170 limit=limit,
5171 tolerance=tolerance,
5172 )
File ~/work/pandas/pandas/pandas/core/generic.py:5629, in NDFrame.reindex(self, labels, index, columns, axis, method, copy, level, fill_value, limit, tolerance)
5626 return self._reindex_multi(axes, copy, fill_value)
5628 # perform the reindex on the axes
-> 5629 return self._reindex_axes(
5630 axes, level, limit, tolerance, method, fill_value, copy
5631 ).__finalize__(self, method="reindex")
File ~/work/pandas/pandas/pandas/core/generic.py:5652, in NDFrame._reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy)
5649 continue
5651 ax = self._get_axis(a)
-> 5652 new_index, indexer = ax.reindex(
5653 labels, level=level, limit=limit, tolerance=tolerance, method=method
5654 )
5656 axis = self._get_axis_number(a)
5657 obj = obj._reindex_with_indexers(
5658 {axis: [new_index, indexer]},
5659 fill_value=fill_value,
5660 copy=copy,
5661 allow_dups=False,
5662 )
File ~/work/pandas/pandas/pandas/core/indexes/base.py:4436, in Index.reindex(self, target, method, level, limit, tolerance)
4433 raise ValueError("cannot handle a non-unique multi-index!")
4434 elif not self.is_unique:
4435 # GH#42568
-> 4436 raise ValueError("cannot reindex on an axis with duplicate labels")
4437 else:
4438 indexer, _ = self.get_indexer_non_unique(target)
ValueError: cannot reindex on an axis with duplicate labels
其他方法,如索引,可能会给出非常令人惊讶的结果。通常,使用标量进行索引会 降低维度。使用标量对 DataFrame
进行切片将返回一个 Series
。使用标量对 Series
进行切片将返回一个标量。但存在重复项时,情况并非如此。
In [5]: df1 = pd.DataFrame([[0, 1, 2], [3, 4, 5]], columns=["A", "A", "B"])
In [6]: df1
Out[6]:
A A B
0 0 1 2
1 3 4 5
列中存在重复项。如果我们对 'B'
进行切片,我们会得到一个 Series
In [7]: df1["B"] # a series
Out[7]:
0 2
1 5
Name: B, dtype: int64
但对 'A'
进行切片会返回一个 DataFrame
In [8]: df1["A"] # a DataFrame
Out[8]:
A A
0 0 1
1 3 4
这同样适用于行标签。
In [9]: df2 = pd.DataFrame({"A": [0, 1, 2]}, index=["a", "a", "b"])
In [10]: df2
Out[10]:
A
a 0
a 1
b 2
In [11]: df2.loc["b", "A"] # a scalar
Out[11]: 2
In [12]: df2.loc["a", "A"] # a Series
Out[12]:
a 0
a 1
Name: A, dtype: int64
重复标签检测#
您可以使用 Index.is_unique
检查 Index
(存储行或列标签)是否唯一。
In [13]: df2
Out[13]:
A
a 0
a 1
b 2
In [14]: df2.index.is_unique
Out[14]: False
In [15]: df2.columns.is_unique
Out[15]: True
注意
对于大型数据集,检查索引是否唯一会消耗一定的资源。pandas 会缓存此结果,因此在同一索引上重新检查会非常快。
Index.duplicated()
将返回一个布尔 ndarray,指示标签是否重复。
In [16]: df2.index.duplicated()
Out[16]: array([False, True, False])
这可以作为布尔过滤器来删除重复行。
In [17]: df2.loc[~df2.index.duplicated(), :]
Out[17]:
A
a 0
b 2
如果您需要额外的逻辑来处理重复标签,而不仅仅是删除重复项,那么在索引上使用 groupby()
是一个常用技巧。例如,我们将通过取所有具有相同标签的行的平均值来解决重复问题。
In [18]: df2.groupby(level=0).mean()
Out[18]:
A
a 0.5
b 2.0
禁止重复标签#
1.2.0 版本新增。
如上所述,在读取原始数据时,处理重复项是一项重要功能。话虽如此,您可能希望避免在数据处理管道中(例如来自 pandas.concat()
、rename()
等方法)引入重复项。Series
和 DataFrame
都通过调用 .set_flags(allows_duplicate_labels=False)
来 禁止 重复标签。(默认是允许它们)。如果存在重复标签,将引发异常。
In [19]: pd.Series([0, 1, 2], index=["a", "b", "b"]).set_flags(allows_duplicate_labels=False)
---------------------------------------------------------------------------
DuplicateLabelError Traceback (most recent call last)
Cell In[19], line 1
----> 1 pd.Series([0, 1, 2], index=["a", "b", "b"]).set_flags(allows_duplicate_labels=False)
File ~/work/pandas/pandas/pandas/core/generic.py:508, in NDFrame.set_flags(self, copy, allows_duplicate_labels)
506 df = self.copy(deep=copy and not using_copy_on_write())
507 if allows_duplicate_labels is not None:
--> 508 df.flags["allows_duplicate_labels"] = allows_duplicate_labels
509 return df
File ~/work/pandas/pandas/pandas/core/flags.py:109, in Flags.__setitem__(self, key, value)
107 if key not in self._keys:
108 raise ValueError(f"Unknown flag {key}. Must be one of {self._keys}")
--> 109 setattr(self, key, value)
File ~/work/pandas/pandas/pandas/core/flags.py:96, in Flags.allows_duplicate_labels(self, value)
94 if not value:
95 for ax in obj.axes:
---> 96 ax._maybe_check_unique()
98 self._allows_duplicate_labels = value
File ~/work/pandas/pandas/pandas/core/indexes/base.py:716, in Index._maybe_check_unique(self)
713 duplicates = self._format_duplicate_message()
714 msg += f"\n{duplicates}"
--> 716 raise DuplicateLabelError(msg)
DuplicateLabelError: Index has duplicates.
positions
label
b [1, 2]
这适用于 DataFrame
的行和列标签。
In [20]: pd.DataFrame([[0, 1, 2], [3, 4, 5]], columns=["A", "B", "C"],).set_flags(
....: allows_duplicate_labels=False
....: )
....:
Out[20]:
A B C
0 0 1 2
1 3 4 5
此属性可以通过 allows_duplicate_labels
进行检查或设置,它指示该对象是否可以有重复标签。
In [21]: df = pd.DataFrame({"A": [0, 1, 2, 3]}, index=["x", "y", "X", "Y"]).set_flags(
....: allows_duplicate_labels=False
....: )
....:
In [22]: df
Out[22]:
A
x 0
y 1
X 2
Y 3
In [23]: df.flags.allows_duplicate_labels
Out[23]: False
DataFrame.set_flags()
可用于返回一个新的 DataFrame
,其 allows_duplicate_labels
等属性设置为某个值。
In [24]: df2 = df.set_flags(allows_duplicate_labels=True)
In [25]: df2.flags.allows_duplicate_labels
Out[25]: True
返回的新 DataFrame
是旧 DataFrame
相同数据的视图。或者该属性可以直接在同一个对象上设置。
In [26]: df2.flags.allows_duplicate_labels = False
In [27]: df2.flags.allows_duplicate_labels
Out[27]: False
在处理原始的、杂乱的数据时,您可能会首先读取这些杂乱数据(其中可能包含重复标签),然后去重,并在后续操作中禁止重复,以确保您的数据管道不会引入重复项。
>>> raw = pd.read_csv("...")
>>> deduplicated = raw.groupby(level=0).first() # remove duplicates
>>> deduplicated.flags.allows_duplicate_labels = False # disallow going forward
在包含重复标签的 Series
或 DataFrame
上设置 allows_duplicate_labels=False
,或在禁止重复标签的 Series
或 DataFrame
上执行引入重复标签的操作,将引发 errors.DuplicateLabelError
。
In [28]: df.rename(str.upper)
---------------------------------------------------------------------------
DuplicateLabelError Traceback (most recent call last)
Cell In[28], line 1
----> 1 df.rename(str.upper)
File ~/work/pandas/pandas/pandas/core/frame.py:5774, in DataFrame.rename(self, mapper, index, columns, axis, copy, inplace, level, errors)
5643 def rename(
5644 self,
5645 mapper: Renamer | None = None,
(...)
5653 errors: IgnoreRaise = "ignore",
5654 ) -> DataFrame | None:
5655 """
5656 Rename columns or index labels.
5657
(...)
5772 4 3 6
5773 """
-> 5774 return super()._rename(
5775 mapper=mapper,
5776 index=index,
5777 columns=columns,
5778 axis=axis,
5779 copy=copy,
5780 inplace=inplace,
5781 level=level,
5782 errors=errors,
5783 )
File ~/work/pandas/pandas/pandas/core/generic.py:1140, in NDFrame._rename(self, mapper, index, columns, axis, copy, inplace, level, errors)
1138 return None
1139 else:
-> 1140 return result.__finalize__(self, method="rename")
File ~/work/pandas/pandas/pandas/core/generic.py:6281, in NDFrame.__finalize__(self, other, method, **kwargs)
6274 if other.attrs:
6275 # We want attrs propagation to have minimal performance
6276 # impact if attrs are not used; i.e. attrs is an empty dict.
6277 # One could make the deepcopy unconditionally, but a deepcopy
6278 # of an empty dict is 50x more expensive than the empty check.
6279 self.attrs = deepcopy(other.attrs)
-> 6281 self.flags.allows_duplicate_labels = other.flags.allows_duplicate_labels
6282 # For subclasses using _metadata.
6283 for name in set(self._metadata) & set(other._metadata):
File ~/work/pandas/pandas/pandas/core/flags.py:96, in Flags.allows_duplicate_labels(self, value)
94 if not value:
95 for ax in obj.axes:
---> 96 ax._maybe_check_unique()
98 self._allows_duplicate_labels = value
File ~/work/pandas/pandas/pandas/core/indexes/base.py:716, in Index._maybe_check_unique(self)
713 duplicates = self._format_duplicate_message()
714 msg += f"\n{duplicates}"
--> 716 raise DuplicateLabelError(msg)
DuplicateLabelError: Index has duplicates.
positions
label
X [0, 2]
Y [1, 3]
此错误消息包含重复的标签,以及 Series
或 DataFrame
中所有重复项(包括“原始项”)的数字位置。
重复标签传播#
通常,禁止重复是“粘性的”。它在操作中会保留。
In [29]: s1 = pd.Series(0, index=["a", "b"]).set_flags(allows_duplicate_labels=False)
In [30]: s1
Out[30]:
a 0
b 0
dtype: int64
In [31]: s1.head().rename({"a": "b"})
---------------------------------------------------------------------------
DuplicateLabelError Traceback (most recent call last)
Cell In[31], line 1
----> 1 s1.head().rename({"a": "b"})
File ~/work/pandas/pandas/pandas/core/series.py:5101, in Series.rename(self, index, axis, copy, inplace, level, errors)
5094 axis = self._get_axis_number(axis)
5096 if callable(index) or is_dict_like(index):
5097 # error: Argument 1 to "_rename" of "NDFrame" has incompatible
5098 # type "Union[Union[Mapping[Any, Hashable], Callable[[Any],
5099 # Hashable]], Hashable, None]"; expected "Union[Mapping[Any,
5100 # Hashable], Callable[[Any], Hashable], None]"
-> 5101 return super()._rename(
5102 index, # type: ignore[arg-type]
5103 copy=copy,
5104 inplace=inplace,
5105 level=level,
5106 errors=errors,
5107 )
5108 else:
5109 return self._set_name(index, inplace=inplace, deep=copy)
File ~/work/pandas/pandas/pandas/core/generic.py:1140, in NDFrame._rename(self, mapper, index, columns, axis, copy, inplace, level, errors)
1138 return None
1139 else:
-> 1140 return result.__finalize__(self, method="rename")
File ~/work/pandas/pandas/pandas/core/generic.py:6281, in NDFrame.__finalize__(self, other, method, **kwargs)
6274 if other.attrs:
6275 # We want attrs propagation to have minimal performance
6276 # impact if attrs are not used; i.e. attrs is an empty dict.
6277 # One could make the deepcopy unconditionally, but a deepcopy
6278 # of an empty dict is 50x more expensive than the empty check.
6279 self.attrs = deepcopy(other.attrs)
-> 6281 self.flags.allows_duplicate_labels = other.flags.allows_duplicate_labels
6282 # For subclasses using _metadata.
6283 for name in set(self._metadata) & set(other._metadata):
File ~/work/pandas/pandas/pandas/core/flags.py:96, in Flags.allows_duplicate_labels(self, value)
94 if not value:
95 for ax in obj.axes:
---> 96 ax._maybe_check_unique()
98 self._allows_duplicate_labels = value
File ~/work/pandas/pandas/pandas/core/indexes/base.py:716, in Index._maybe_check_unique(self)
713 duplicates = self._format_duplicate_message()
714 msg += f"\n{duplicates}"
--> 716 raise DuplicateLabelError(msg)
DuplicateLabelError: Index has duplicates.
positions
label
b [0, 1]
警告
这是一个实验性功能。目前,许多方法未能传播 allows_duplicate_labels
值。在未来的版本中,预计每个接收或返回一个或多个 DataFrame 或 Series 对象的方法都将传播 allows_duplicate_labels
。