KeyError when running this part of code in Section 5, Unit 15

Course Name: Python for Trading: Basic, Section No: 5, Unit No: 15, Unit type: Notebook



infy.head() and infy.tail() show he right table, with columns, but when I run the next part, I get the following error:



infy_close = infy [['Date','close']]

infy_close.set_index('Date', inplace=True)

infy_close

 

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-38-b1918072bb69> in <module>
----> 1 infy_close = infy [['Date','close']]
      2 infy_close.set_index('Date', inplace=True)
      3 infy_close


~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/frame.py in __getitem__(self, key)
   2906             if is_iterator(key):
   2907                 key = list(key)
-> 2908             indexer = self.loc._get_listlike_indexer(key, axis=1, raise_missing=True)[1]
   2909 
   2910         # take() does not accept boolean indexers

 

You can try slicing using loc property.



Try this:



infy_close = infy.loc[:,['Date','close']] 

infy_close.set_index('Date', inplace=True) 

infy_close