Python If Statement Dictionary Incompatible Indexer with Series

Python If Statement Dictionary Incompatible Indexer with Series

This script :

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

gives this error :

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

But the script is working, meaning df.loc[x,'coutmed1'] takes the value that I want.

I don't understand what am I doing wrong ?

I think that the problem comes from this

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

4 Answers

This problem occurs when a key in the dict refers to more than one value !

1

Solution: Remove the duplicate indexes from the series (i.e. dicoprix) and keep them unique

You got it, the problem is in dicoprix[df.loc[x,'medicament1']]

There are duplicates in the indexes of the series dicoprix, which cannot be put as one value in the dataframe.

Below is the demonstration:

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

Following command will run fine as 'a' is not the duplicate index in dum_ser series

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

Error will occur when the command tries to insert two records from the series(as there are two records for the index b in dum_ser, to check run the command dum_ser['b']) into one value-space of the DataFrame. Refer below

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

The above-written line of the code is the one of the iteration from the for loop i.e. for x=1

Solution: Remove the duplicate indexes from the series (i.e. dum_ser here) and keep them unique

1

I had a same problem, in

for i, (result, status) in enumerate(results):
    df.at[i, 'response'] = result

And this error, how I understand, can mean that type of value what you try assign does not match the column type in the dataframe
In my case result was a dict, because it response post request
Solution is easy - cast type to string:

for i, (result, status) in enumerate(results):
        df.at[i, 'response'] = str(result)

Use indexing like this:

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

It did work for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.