'Dataframe KeyError:

This is my data frame code:

result = pd.read_csv("learning_1.csv")

enter image description here

Then when I want to check the diagnosis it turns out that it showed key error

result["Diagnosis"]

It show KeyError: 'Diagnosis'.

    KeyError                                  Traceback (most recent call last)
<ipython-input-119-76b8b4a21668> in <module>
----> 1 result["Diagnosis"]

c:\python\python3.8\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2798             if self.columns.nlevels > 1:
   2799                 return self._getitem_multilevel(key)
-> 2800             indexer = self.columns.get_loc(key)
   2801             if is_integer(indexer):
   2802                 indexer = [indexer]

c:\python\python3.8\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2646                 return self._engine.get_loc(key)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2650         if indexer.ndim > 1 or indexer.size > 1:

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.PyObjectHashTable.get_item()

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

KeyError: 'Diagnosis'


Solution 1:[1]

Maybe there is some space or hidden character in the column name.

Try excecuting "result.columns" and see the output.

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 Liutprand