Pandas - KeyError:列不在索引中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41406394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:41:37 来源:igfitidea点击:
Pandas - KeyError: columns not in index
提问by Suraj Kumar Singh
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:“['Adj.Open' 'Adj.High' 'Adj.Low' 'Adj.Close' 'Adj.Volume'] 不在索引中”
回答by jezrael
You need spaces in columns names - after .
add one space:
列名称中需要空格 -.
添加一个空格后:
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
If solution above not working, you can try:
如果上述解决方案不起作用,您可以尝试:
#pandas below 0.24+
print (df.columns.values.tolist())
#pandas above 0.24+
print (df.columns.to_numpy().tolist())