首页 > 解决方案 > 为什么错误'上述异常是以下异常的直接原因:'出现在Python上

问题描述

我正在尝试使用 nlargest 处理我的 CSV,但我遇到了这个错误。为什么会这样?我试图绕过它,但它似乎并没有消失。

import pandas as pd
from matplotlib import pyplot
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from pandas import read_csv
from pandas.plotting import scatter_matrix


filename = '/Users/rahulparmeshwar/Documents/Algo Bots/Data/Live Data/Tester.csv'
data = pd.read_csv(filename)
columnname = 'Scores'
bestfeatures = SelectKBest(k='all')
y = data['Vol']
X = data.drop('Open',axis=1)
fit = bestfeatures.fit(X,y)
dfscores = pd.DataFrame(fit.scores_)
dfcolumns = pd.DataFrame(X.columns)
featurescores = pd.concat([dfscores,dfcolumns],axis=1)
print(featurescores.nlargest(5,[columnname]))

它给了我错误Scores,上面的异常是最后一行出现以下异常的直接原因print(featurescores.nlargest(5,[columnname]))。有人可以向我解释为什么会这样吗?我环顾四周,似乎无法弄清楚这一点。

编辑:完整的错误堆栈:

Exception has occurred: KeyError 'Scores'

上述异常是以下异常的直接原因:

File "C:\Users\mattr\OneDrive\Documents\Python AI\AI.py", line 19, in <module> print(featurescores.nlargest(2,'Scores'))

标签: python-3.xcsvsklearn-pandaskeyerror

解决方案


异常KeyError意味着连接的数据框featurescores没有名为“Scores”的列。

问题是创建的 DataFramesdfscores并且dfcolumns没有明确定义列名,因此它们的单个列名将是 "default" 0。也就是说,在连接之后,您会得到一个featurescores类似于以下内容的 DataFrame ( ):

           0         0
0         xxx     col1_name
1         xxx     col2_name
2         xxx     col3_name
...

如果要按名称引用列,则应显式定义列名称,如下所示:

>>> dfscores = pd.DataFrame(fit.scores_, columns=["Scores"])
>>> dfcolumns = pd.DataFrame(X.columns, columns=["Features"])
>>> featurescores = pd.concat([dfscores,dfcolumns], axis=1)
>>> print(featurescores.nlargest(5, "Scores"))

       Scores   Features
0       xxx       col_name1
1       xxx       col_name2
2       xxx       col_name3
...

如果您想使用这些功能作为索引,这里有一个衬里:

>>> featurescores = pd.DataFrame(data=fit.scores_.transpose(), index=X.columns.transpose(), columns=["Scores"])
>>> print(featurescores)

               Scores
col_name1       xxx
col_name2       xxx
col_name3       xxx
...

推荐阅读