Trust 列中的脊柱文件确实包含重复值,因为每行描述了 Trust 内各个医生的手术活动,并且该系列中最多有 10 名医生(因此有 10 个重复的 Trust 名称)。
这就是问题所在。当索引重复时,pandas 不知道使用哪个值。请参阅下面的示例。
import pandas as pd
s = pd.Series(['cat', 'dog', 'rabbit', 'cat'])
s
## Out
0 cat
1 dog
2 rabbit
3 cat
dtype: object
s2 = pd.Series(['carnivore', 'omnivore', 'herbivore', 'carnivore'])
# Set the value of `s` as the index of `s2`, since map looks at the Series index.
s2.index = s
s2
## Out
cat carnivore
dog omnivore
rabbit herbivore
cat carnivore
dtype: object
由于有两次出现cat
在索引中s2
,pandas 不知道映射时使用哪个值s2
to s
(您可以说动物与猫的进食行为存在一对二的映射)。因此,现在尝试使用地图会抛出InvalidIndexError
:
s.map(s2)
## Out
---------------------------------------------------------------------------
InvalidIndexError Traceback (most recent call last)
<ipython-input-43-1950a0742767> in <module>()
----> 1 s.map(s2)
~/miniconda3/envs/ds/lib/python3.7/site-packages/pandas/core/series.py in map(self, arg, na_action)
3826 dtype: object
3827 """
-> 3828 new_values = super()._map_values(arg, na_action=na_action)
3829 return self._constructor(new_values, index=self.index).__finalize__(self)
3830
~/miniconda3/envs/ds/lib/python3.7/site-packages/pandas/core/base.py in _map_values(self, mapper, na_action)
1275 values = self.values
1276
-> 1277 indexer = mapper.index.get_indexer(values)
1278 new_values = algorithms.take_1d(mapper._values, indexer)
1279
~/miniconda3/envs/ds/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_indexer(self, target, method, limit, tolerance)
2983 if not self.is_unique:
2984 raise InvalidIndexError(
-> 2985 "Reindexing only valid with uniquely" " valued Index objects"
2986 )
2987
InvalidIndexError: Reindexing only valid with uniquely valued Index objects
您需要检查重复值并决定使用哪一个。你可以这样做:
s2[s2.index.duplicated(keep=False)]
## Out
cat carnivore
cat carnivore
dtype: object
在这种情况下,两个值cat
是相同的,我们可以摆脱其中任何一个(您的描述表明在您的情况下是相同的)。如果它们不同,您就必须选择保留哪一个。
# `~` negates/inverses the indexing
s2 = s2[~s2.index.duplicated()]
s2
## Out
cat carnivore
dog omnivore
rabbit herbivore
dtype: object
s2
现在有了动物与进食行为的一对一映射,我们可以安全地映射s2
onto s
.
s.map(s2)
## Out
0 carnivore
1 omnivore
2 herbivore
3 carnivore
dtype: object