Observing Key error on the code

Hi All,

Observing “KeyError” on the below code , Please give some ideas to solve the same.

import pandas as pd
import matplotlib.pyplot as plt
import time

df = pd.read_excel("/home/karthika.s1/Desktop/Discovery_system_profile-Thu-Mar-19-11-03-35-UTC-20201.xls")

df.plot(kind=‘line’,color=‘y’, x=‘Date’,y=‘Memory’)
plt.title(“Server Metrics chart”)

Error Observed :

~/.local/lib/python3.6/site-packages/pandas/plotting/_core.py in call(self, *args, **kwargs)
832 # don’t overwrite
–> 833 data = data[y].copy()
835 if isinstance(data, ABCSeries):

~/.local/lib/python3.6/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]

~/.local/lib/python3.6/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: ‘Memory’

Error shows problem with key Memory - so first check if you have this column in your DataFarme (before you use y="Memory").

EDIT: I found your question on Stackoverflow

Error shows you have columns

Expected one of ['Date', ' Memory', 'CPU', ' Memory1', ...

So column name has space at the beginning and you have to respect it

y=' Memory'

Or you have to remove spaces from names

import pandas as pd

df = pd.DataFrame({' Memory': [], ' Memory1': []})
print('Before:', df.columns)

df.columns = df.columns.str.strip()
print(' After:', df.columns)


Before: Index([' Memory', ' Memory1'], dtype='object')
 After: Index(['Memory', 'Memory1'], dtype='object'
© Copyright 2013-2019 Analytics Vidhya