Maryam Anwer
Maryam Anwer

Reputation: 43

KeyError when plotting pandas dataframe with matplotlib

I use weather data csv and when i plot wind it show keyword error

Here is my data:

    Year    Month   Day Hour    Temperature Wind
0   2019    3   18  0   22.02   7.42
1   2019    3   18  1   21.48   6.88
2   2019    3   18  2   21.09   6.84
3   2019    3   18  3   20.75   7.20
4   2019    3   18  4   20.43   7.56

Now when i attempt to plot

import matplotlib  
import matplotlib.pyplot as plt  
import numpy as np  
plt.plot( data['Wind'])
plt.title('Wind Speed')

plt.ylim(0.0, 10.5 )
plt.ylim(0.0, 20.09)
plt.show()

It show this error

KeyError                                  Traceback (most recent call last)
~/anaconda3/envs/tesnorenv/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2655             try:
-> 2656                 return self._engine.get_loc(key)
   2657             except KeyError:

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: 'Wind'


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

KeyError: 'Wind'

When i use Day, Month and hour it plot right but it not working in Temperature and Wind

It work fine. Please help me i can't find error

Upvotes: 1

Views: 3298

Answers (1)

EdChum
EdChum

Reputation: 393903

Your columns have spaces:

['Year' 'Month' 'Day' 'Hour' 'Temperature ' 'Wind '] 

You can see that 'Temperature ' and 'Wind ' have trailing spaces.

Whenever you see a KeyError then you should look at what your columns really are, not what they look like by doing print(data.columns.tolist())

So you can either call the column correctly:

plt.plot( data['Wind '])

or clean up the columns:

data.columns = data.columns.str.strip()

to remove leading and trailing spaces

Upvotes: 2

Related Questions