2016-12-31 208 views
-2
import pandas as pd 
import quandl 

df=quandl.get('WIKI/GOOGL') 

#print(df.head()) 

df=df[['Adj.Open','Adj.High','Adj.Low','Adj.Close','Adj.Volume']] 

df['HL_PCT'] =(df['Adj.High']-df['Adj.Close'])/df['Adj.Close'] * 100 

df['PCT_change'] =(df['Adj.Close']-df['Adj.Open'])/df['Adj.Open'] * 100 

df=df[['Adj.Close','HT_PCT','PCT_change','Adj.Volume']] 

KeyError: "['Adj.Open' 'Adj.High' 'Adj.Low' 'Adj.Close' 'Adj.Volume'] not in index"熊貓 - KeyError異常:列不在索引

+0

什麼是'打印(df.columns .tolist())'?看起來在按名稱選擇列時存在一些錯字。 – jezrael

+2

錯誤在哪裏?在問題中包含完整的錯誤回溯。 – MYGz

回答

3

你需要在列名中的空格 - .後添加一個空格:

print (df.columns.tolist()) 
['Open', 'High', 'Low', 'Close', 'Volume', 'Ex-Dividend', 'Split Ratio', 
'Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume'] 

import pandas as pd 
import quandl 

df=quandl.get('WIKI/GOOGL') 

#print(df.head()) 
#print (df.columns.tolist()) 

df=df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume']] 

df['HL_PCT'] =(df['Adj. High']-df['Adj. Close'])/df['Adj. Close'] * 100 

df['PCT_change'] =(df['Adj. Close']-df['Adj. Open'])/df['Adj. Open'] * 100 

df=df[['Adj. Close','HL_PCT','PCT_change','Adj. Volume']] 
print (df.head()) 
      Adj. Close HL_PCT PCT_change Adj. Volume 
Date              
2004-08-19 50.322842 3.712563 0.324968 44659000.0 
2004-08-20 54.322689 0.710922 7.227007 22834300.0 
2004-08-23 54.869377 3.729433 -1.227880 18256100.0 
2004-08-24 52.597363 6.417469 -5.726357 15247300.0 
2004-08-25 53.164113 1.886792 1.183658 9188600.0