Python Pandas set_index函数:KeyError:"[]中没有一个在列中" [英] Python Pandas set_index function: KeyError: "None of [] are in the columns"

查看:295
本文介绍了Python Pandas set_index函数:KeyError:"[]中没有一个在列中"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在阅读动手机器学习..."一书,由AurèlionGèron设计.但是,我收到以下错误消息:(由于要下载以下两个CSV文件,因此复制起来有些麻烦:

I am currently going through the book "Hands-On machine learning... " by Aurèlion Gèron. However, I am getting the following error message: (it is somewhat cumbersome to reproduce because the following two CSV downloads are required: OECD IMF.

Error message:

File "C:\Users\xxx\Miniconda3\lib\site-packages\pandas\core\frame.py", line 4548, in set_index raise KeyError(f"None of {missing} are in the columns")

KeyError: "None of ['Country'] are in the columns"

The code:

import matplotlib.pyplot as plt 
import numpy as np 
import pandas as pd 
import sklearn.linear_model

oecd_bli = pd.read_csv("BLI_24092020220751169.csv", thousands =',')

gdp_per_capita = pd.read_csv("gdp_per_capita.csv", thousands =',', delimiter ='\t', encoding =' latin1', na_values="n/a")

def prepare_country_stats(oecd_bli, gdp_per_capita):
    oecd_bli = oecd_bli[oecd_bli["INEQUALITY"]=="TOT"]
    oecd_bli = oecd_bli.pivot(index="Country", columns="Indicator", values="Value")
    gdp_per_capita.rename(columns={"2015":"GDP per capita"}, inplace=True)
    gdp_per_capita.set_index("Country", inplace=True)
    full_country_stats = pd.merge(left=oecd_bli, right=gdp_per_capita,
                                  left_index=True, right_index=True)
    full_country_stats.sort_values(by="GDP per capita", inplace=True)
    remove_indices = [0, 1, 6, 8, 33, 34, 35]
    keep_indices = list(set(range(36)) - set(remove_indices))
    return full_country_stats[["GDP per capita", 'Life satisfaction']].iloc[keep_indices]

country_stats = prepare_country_stats(oecd_bli, gdp_per_capita) 
X = np.c_[country_stats["GDP per capita"]] 
y = np.c_[country_stats["Life satisfaction"]] 

# Visualize the data 
country_stats.plot( kind ='scatter', X ="GDP per capita", y ='Life satisfaction') 
plt.show() 

# Select a linear model 
model = sklearn.linear_model.LinearRegression() 

# Train the model 
model.fit(X, y) 

# Make a prediction for Cyprus 
X_new = [[22587]] 
# Cyprus's GDP per capita 

print( model.predict(X_new))

However, already in the function I get stuck. The error seems to be related to the set_index command, which I thought was a very reliable function. Of course, in my CSV file the Country column is present.

Here is a screenshot of the gdp_per_capita CSV.

If anyone takes the time to reproduce, it would be highly appreciated.

解决方案

Couple of changes required in your code:

Change this line:

gdp_per_capita = pd.read_csv("gdp_per_capita.csv", thousands =',', delimiter ='\t', encoding =' latin1', na_values="n/a")

to this (remove the encoding='latin1'):

gdp_per_capita = pd.read_csv("gdp_per_capita.csv", thousands =',', delimiter ='\t', na_values="n/a")

And change this:

country_stats.plot(kind='scatter', X="GDP per capita", y='Life satisfaction')

To this (Capital X to x):

country_stats.plot(kind='scatter', x="GDP per capita", y='Life satisfaction')

I was able to get a scatter plot after these 2 changes:

这篇关于Python Pandas set_index函数:KeyError:"[]中没有一个在列中"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆