我的Jupyter中有以下代码:
import pandas as pd
import quandl
df=quandl.get('WIKI/GOOGL')
print(df.head())
#upto here its working but here comes the error
df=df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume',]]
df['HL_PCT']=(df['Adj. High']-df['Adj. Low'])/df['Adj. Close']
df['PCT_change']=(df['Adj. Close']-df['Adj. Open'])/df['Adj. Open']
df=df[['Adj. Close','HL_PCT','PCT_change','Adj.Volume']]
print(df.head())
这将产生以下错误:
\local\programs\python\python37-32\lib\site-packages\ipykernel_launcher.py:2: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
---------------------------------------------------------------------------
KeyError
Traceback (most recent call last)
<ipython-input-11-c981ac0a05ec> in <module>()
2 df['HL_PCT']=(df['Adj. High']-df['Adj. Low'])/df['Adj. Close']*100.0
3 df['PCT_change']=(df['Adj. Close']-df['Adj. Open'])/df['Adj. Open']*100.0
----> 4 df=df[['Adj. Close','HL_PCT','PCT_change','Adj.Volume']]
5 print(df.head())
c:\users\xyz\appdata\local\programs\python\python37-32\lib\site-
packages\pandas\core\frame.py in __getitem__(self, key)
2680 if isinstance(key, (Series, np.ndarray, Index, list)):
2681 # either boolean or fancy integer index
-> 2682 return self._getitem_array(key)
2683 elif isinstance(key, DataFrame):
2684 return self._getitem_frame(key)
c:\users\xyz\appdata\local\programs\python\python37-32\lib\site-packages\pandas\core\frame.py in _getitem_array(self, key)
2724 return self._take(indexer, axis=0)
2725 else:
-> 2726 indexer = self.loc._convert_to_indexer(key, axis=1)
2727
return self._take(indexer, axis=1)
2728
c:\users\xyz\appdata\local\programs\python\python37-32\lib\site-packages\pandas\core\indexing.py in _convert_to_indexer(self, obj, axis, is_setter)
1325 if mask.any():
1326 raise KeyError('{mask} not in index'
-> 1327 .format(mask=objarr[mask]))
1328
1329 return com._values_from_object(indexer)
KeyError: "['Adj.Volume'] not in index"
你能帮助我吗?
最佳答案
在“ Adj.Volume”中,您忘记添加空格,这就是为什么它找不到您指定的列的原因。
这行:
df=df[['Adj. Close','HL_PCT','PCT_change','Adj.Volume']]
应该是这样的:
df=df[['Adj. Close','HL_PCT','PCT_change','Adj. Volume']]
编辑:
下面的代码正在工作:
import pandas as pd
import quandl
df=quandl.get('WIKI/GOOGL')
df=df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume']]
df['HL_PCT']=(df['Adj. High']-df['Adj. Low'])/df['Adj. Close']
df['PCT_change']=(df['Adj. Close']-df['Adj. Open'])/df['Adj. Open']
df=df[['Adj. Close','HL_PCT','PCT_change','Adj. Volume']]
print(df.head())
关于python - 如何在python机器学习中解决索引中没有列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52551909/