python-3.x - 为什么错误'上述异常是以下异常的直接原因:'出现在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”的列。
问题是创建的 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
...
推荐阅读
- html - 如何在 TAB 中的按钮上放置按钮?
- python - 如何从数据框中删除 NBA 球员的位置并创建一个新列“位置”?
- android - E/Unity:DllNotFoundException:无法加载 DLL 'FirebaseCppApp-7_1_0':[已解决]
- azure-devops - 从管道构建-发布-部署将参数传递给 Blazor WebAssembly
- postgresql - 如何通过 Github 工作流部署 SQL 文件?
- python - 如何在文本的卷积层中使用 tensorflow hub 层嵌入?
- flutter - Flutter Golden 测试 - 加载内置字体
- python - 自动化打开的 Firefox 浏览器 - Selenium
- reactjs - axios请求成功后如何打开模式
- python - 切片列表和写入数据库上的 Python 内存泄漏