python if语句字典与Series不兼容的索引器

新手上路,请多包涵

这个脚本:

 for x in df.index:
    if df.loc[x,'medicament1'] in dicoprix:
        df.loc[x,'coutmed1'] = dicoprix[df.loc[x,'medicament1']]

给出此错误:

 File "<ipython-input-35-097fdb2220b8>", line 3, in <module>
    df.loc[x,'coutmed1'] = dicoprix[df.loc[x,'medicament1']]

  File "//anaconda/lib/python2.7/site-packages/pandas/core/indexing.py", line 115, in __setitem__
    self._setitem_with_indexer(indexer, value)

  File "//anaconda/lib/python2.7/site-packages/pandas/core/indexing.py", line 346, in _setitem_with_indexer
    value = self._align_series(indexer, value)

  File "//anaconda/lib/python2.7/site-packages/pandas/core/indexing.py", line 613, in _align_series
    raise ValueError('Incompatible indexer with Series')

ValueError: Incompatible indexer with Series

但是脚本正在运行,这意味着 df.loc[x,'coutmed1'] 采用了我想要的值。

我不明白我做错了什么?

我认为问题来自于此

dicoprix[df.loc[x,'medicament1']]

原文由 salim 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 671
2 个回答

当 dict 中的一个键引用多个值时会出现此问题!

原文由 salim 发布,翻译遵循 CC BY-SA 3.0 许可协议

解决方案:从系列(即dicoprix)中删除重复的索引并保持它们的唯一性

你明白了,问题出在 dicoprix[df.loc[x,'medicament1']]

系列 dicoprix 的索引中存在重复项,不能将其作为一个值放入数据框中。

下面是演示:

 In [1]:
import pandas as pd
dum_ser = pd.Series(index=['a','b','b','c'], data=['apple', 'balloon', 'ball', 'cat' ])

[Out 1]
a      apple
b    balloon
b       ball
c        cat
dtype: object

In [2]:
df = pd.DataFrame({'letter':['a','b','c','d'], 'full_form':['aley', 'byue', 'case', 'cible']}, index=[0,1,2,3])
df

Out [2]:
    letter  full_form
0   a   aley
1   b   byue
2   c   case
3   d   cible

以下命令运行良好,因为“a”不是 dum_ser 系列中的重复索引

In [3]:
df.loc[0,'full_form'] = dum_ser['a']
df

Out [3]:
    letter  full_form
0   a   apple
1   b   byue
2   c   case
3   d   apple

当命令尝试从系列中插入两条记录时会发生错误(因为索引 bdum_ser 中有两条记录,以检查运行命令 dum_ser['b'] ) 到 DataFrame 的一个值空间。参考以下

In [4]:
df.loc[1,'full_form'] = dum_ser['b']

Out [4]:
    ---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-af11b9b3a776> in <module>()
----> 1 df.loc['b','full_form'] = dum_ser['b']

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in __setitem__(self, key, value)
    187             key = com._apply_if_callable(key, self.obj)
    188         indexer = self._get_setitem_indexer(key)
--> 189         self._setitem_with_indexer(indexer, value)
    190
    191     def _validate_key(self, key, axis):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _setitem_with_indexer(self, indexer, value)
    635                 # setting for extensionarrays that store dicts. Need to decide
    636                 # if it's worth supporting that.
--> 637                 value = self._align_series(indexer, Series(value))
    638
    639             elif isinstance(value, ABCDataFrame):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _align_series(self, indexer, ser, multiindex_indexer)
    775             return ser.reindex(ax)._values
    776
--> 777         raise ValueError('Incompatible indexer with Series')
    778
    779     def _align_frame(self, indexer, df):

ValueError: Incompatible indexer with Series

上面写的代码行是来自 for 循环的迭代之一,即对于 x=1

解决方案:删除系列中的重复索引(即 dum_ser 此处)并保持唯一

原文由 Ankit Moral 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题