我试图根据获胜党派进行预测。我选择的数据集中的列是候选党派和候选人的得票数。我的代码如下:
# 加载和清理数据集df4 = pd.read_csv('Election-Results-2018 - Parlimen_Results_By_Candidate.csv')df4['Votes for Candidate'] = df4['Votes for Candidate'].str.replace(',','').astype(float)df4['Total Votes Cast'] = df4['Total Votes Cast'].str.replace(',','').astype(float)df4['% of total Votes'] = df4['% of total Votes'].str.replace('%','').astype(float)# 步骤1 - 导入模型 from sklearn.linear_model import LogisticRegression# 步骤2 - 定义训练数据columns = ['Candidate Party', 'Votes for Candidate']# 步骤3 - 创建训练数据集X = df[columns]y = df['New Results']*
运行这些代码后,我收到了如下错误:
KeyError: "None of [Index(['Candidate Party', 'Votes for Candidate'], dtype='object')] are in the [columns]"
我是机器学习的初学者,希望能得到任何人的帮助和指导。谢谢
回答:
这是一个简单的错误,你使用了错误的名称 df
而不是 df4
,这样应该可以工作:
df4 = pd.read_csv('Election-Results-2018 - Parlimen_Results_By_Candidate.csv')df4['Votes for Candidate'] = df4['Votes for Candidate'].str.replace(',','').astype(float)df4['Total Votes Cast'] = df4['Total Votes Cast'].str.replace(',','').astype(float)df4['% of total Votes'] = df4['% of total Votes'].str.replace('%','').astype(float)# 步骤1 - 导入模型 from sklearn.linear_model import LogisticRegression# 步骤2 - 定义训练数据columns = ['Candidate Party', 'Votes for Candidate']# 步骤3 - 创建训练数据集X = df4[columns]y = df4['New Results']