为什么错误"上述异常是以下异常的直接原因:"出现在 Python 上



我试图让我的CSV与nlarge处理,我已经遇到了这个错误。有什么原因吗?我试着去理解它,但它似乎就是没有消失。

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:UsersmattrOneDriveDocumentsPython AIAI.py", line 19, in <module> print(featurescores.nlargest(2,'Scores'))

异常KeyError表示连接的数据框featurescores没有名为"Scores"的列。

问题是创建的DataFramesdfscoresdfcolumns没有明确定义列名,因此它们的单个列名将是"default"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
...

相关内容

  • 没有找到相关文章

最新更新