我正在阅读掌握金融大熊猫这本书,并为S& P 500创建了以下DataFrame:
sp500 = pd.read_csv("sp500.csv", index='Symbol', usecols=[0, 2, 3, 7])
返回以下DataFrame:
练习的一部分是使用以下代码显示仅包含选择列的数据框:
$ sp500[[1, 2]].head(3)
哪个应生成以下DataFrame:
S&P 500 DataFrame with Indexed Columns Only
当我运行代码时,我收到以下错误:
KeyError: '[1 2] not in index'
回溯
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-67-9993ec8d3122> in <module>()
----> 1 sp500[[1, 2]].head(3)
~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key)
1956 if isinstance(key, (Series, np.ndarray, Index, list)):
1957 # either boolean or fancy integer index
-> 1958 return self._getitem_array(key)
1959 elif isinstance(key, DataFrame):
1960 return self._getitem_frame(key)
~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in _getitem_array(self, key)
2000 return self.take(indexer, axis=0, convert=False)
2001 else:
-> 2002 indexer = self.loc._convert_to_indexer(key, axis=1)
2003 return self.take(indexer, axis=1, convert=True)
2004
~/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py in _convert_to_indexer(self, obj, axis, is_setter)
1229 mask = check == -1
1230 if mask.any():
-> 1231 raise KeyError('%s not in index' % objarr[mask])
1232
1233 return _values_from_object(indexer)
KeyError: '[1 2] not in index'
答案 0 :(得分:0)
从图片中看,sp500
列的名称似乎是sector
,price
和book value
。所以大熊猫抱怨,因为你问的是名为1
和2
的列。
sp500[sp500.columns[[1,2]]]
将为您提供第二和第三列,我认为这就是您所追求的目标。