为什么错误 'The above exception was the direct cause of the following exception:' 出现在 Python

Why does the error 'The above exception was the direct cause of the following exception:' come up on 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'))

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

问题是创建的 DataFrame dfscoresdfcolumns 没有明确定义列名,因此它们的单个列名将是“默认”0。 也就是说,在连接之后你会得到一个类似这样的数据帧(featurescores):

           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
...