Dance Party
Dance Party

Reputation: 3723

MatPlotLib Key Error: 0 When Annotating

In this bit of code, I am trying to create a bar chart with one bar (as the "total" bar which will be placed next to other bars) with a slice of a data frame. It works for the other slice of the data frame, but for the "total" slice (which is just one row), I keep getting this "Key Error: 0":

x_4t = dfCOPN['Percent'][-1:]
y_4t = dfCOPN['index'][-1:]
ind4t = np.arange(len(y_4t))

...

for i, text in enumerate(ind4t):
    if x_4t<72:
        ax4t.annotate(str(x_4t)[:-2]+"%", xy=(x_4t+2,ind4t+0.4),fontsize=9, color='black', va='center', ha='left')
    elif x_4t>=72:
        ax4t.annotate(str(x_4t[i])[:-2]+"%", xy=(x_4t[i]-2,ind4t[i]+0.4),fontsize=9, color='white', va='center', ha='right')

Here's the error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-42-e192a1699cc5> in <module>()
    174 #    for i, text in enumerate(ind4t):
--> 175     if x_4t<72:
    176         ax4t.annotate(str(x_4t)[:-2]+"%", xy=(x_4t+2,ind4t+0.4),fontsize=9, color='black', va='center', ha='left')

C:\Users\m\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
    729                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 730                          .format(self.__class__.__name__))
    731 

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-42-e192a1699cc5> in <module>()
    185 except:
    186     for i, text in enumerate(ind4t):
--> 187             ax4t.annotate(str(x_4t[i])[:-2]+"%", xy=(x_4t[i]+2,ind4t[i]+0.4),fontsize=9, color='black', va='center', ha='left')
    188     for i, text in enumerate(ind5t):
    189             ax5t.annotate(str(x_5t[i])[:-2]+"%", xy=(x_5t[i]+2,ind5t[i]+0.4),fontsize=9, color='black', va='center', ha='left')

C:\Users\m\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    549     def __getitem__(self, key):
    550         try:
--> 551             result = self.index.get_value(self, key)
    552 
    553             if not np.isscalar(result):

C:\Users\m\Anaconda3\lib\site-packages\pandas\core\index.py in get_value(self, series, key)
   1721 
   1722         try:
-> 1723             return self._engine.get_value(s, k)
   1724         except KeyError as e1:
   1725             if len(self) > 0 and self.inferred_type in ['integer','boolean']:

pandas\index.pyx in pandas.index.IndexEngine.get_value (pandas\index.c:3204)()

pandas\index.pyx in pandas.index.IndexEngine.get_value (pandas\index.c:2903)()

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:3843)()

pandas\hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6525)()

pandas\hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6463)()

KeyError: 0

I'll send a complete example if needed, but I just wanted to see if the answer is obvious enough to not do so.

Thanks in advance!

Upvotes: 1

Views: 1126

Answers (1)

tacaswell
tacaswell

Reputation: 87596

TL;DR; use iloc

x4t.iloc[0]   

The problem is that pd.Series use index not position indexing via []. This is a powerful idea/bit of syntax as frequently when you are working with a Series the value of the index is the interesting thing, not the position in the Series (ex a date index), however if you expect that Series / DataFrames will behave exactly like a numpy array you will have issues (I speak from experience here).

Upvotes: 5

Related Questions