本文介绍了 pandas -KeyError:列不在索引中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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']]

推荐答案

您需要在列名称中添加空格-在之后.添加一个空格:

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())

这篇关于 pandas -KeyError:列不在索引中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 22:11