'KeyError: 0 in if clause?

I try to plot the following dataframe:

x | y | end_x | end_y | outcome
94.8 | 34.4 | 91.2  | 4.0 | Successful
10.5 | 20.4| 52.3 | 55.8 | Unsuccessful
13.2 | 29.8 | 58.9 | 1.0 | Successful

I cannot figure out what I do wrong here:

for x in range(len(df['x'])):
    if df['outcome'][x] == 'Successful':
        plt.plot((df['x'][x],df['end_x'][x]),(df['y'][x],df['end_y'][x]),color='green')

I try to plot the rows only if df['outcome'] is equal to 'Successful'.

But I get this KeyError:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3079             try:
-> 3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-116-cb16460cada0> in <module>
     10 
     11 for x in range(len(df['x'])):
---> 12     if df['outcome'][x] == 'Successful':
     13         plt.plot((df['x'][x],df['end_x'][x]),(df['y'][x],df['end_y'][x]),color='green')

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    851 
    852         elif key_is_scalar:
--> 853             return self._get_value(key)
    854 
    855         if is_hashable(key):

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
    959 
    960         # Similar to Index.get_value, but we do not fall back to positional
--> 961         loc = self.index.get_loc(label)
    962         return self.index._get_values_for_loc(self, loc, label)
    963 

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:
-> 3082                 raise KeyError(key) from err
   3083 
   3084         if tolerance is not None:

KeyError: 0

What do I have to check here?



Solution 1:[1]

Try this code in your editor:-

data = [[94.8,34.4 , 91.2  , 4.0 , "Successful"], [10.5 , 20.4, 52.3 , 55.8 
, "Unsuccessful"],[13.2 , 29.8 , 58.9 , 1.0 , "Successful"]]
import pandas as pd 
df = pd.DataFrame(data, columns=["x" , "y" , "end_x" , 'end_y' , 
"outcome"])
import matplotlib.pyplot as plt
for x in range(len(df['x'])):
    if df['outcome'][x] == 'Successful':
        plt.plot((df['x'][x],df['end_x'][x]),(df['y'][x],df['end_y'] 
[x]),color='green')

Solution 2:[2]

I now figured out why I got this error. I created this dataframe by removing some rows based on column values of an existing dataframe. Therefore, I did not have continuous index values starting at 0. Therefore, I reset the index and then everything worked out because I then got a continuous index.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 prem sagar kushwaha
Solution 2 Tobitor