英文:
Cannot find key in imported dataframe despite the key being present
问题
I have a panel dataset about the Internet Penetration Rate
of 11 countries and I want to encode the Country
values.
Country Year Int Pen Rate % GDP Per Capita GDP Growth %
0 Australia 2014 84.000000 76864.54828 2.579017
1 Australia 2015 84.560515 77397.27020 2.152736
2 Australia 2016 86.540000 78278.37956 2.730548
3 Australia 2017 86.545049 78751.93511 2.282184
4 Australia 2018 90.000000 79813.73387 2.883045
Why do I get KeyError on Country
when I use the following function?
series['Country'] = label_encoder.fit_transform(series['Country'])
I used sep=','
when I read the dataset.
英文:
I have a panel dataset about the Internet Penetration Rate
of 11 countries and I want to encode the Country
values.
Country Year Int Pen Rate % GDP Per Capita GDP Growth %
0 Australia 2014 84.000000 76864.54828 2.579017
1 Australia 2015 84.560515 77397.27020 2.152736
2 Australia 2016 86.540000 78278.37956 2.730548
3 Australia 2017 86.545049 78751.93511 2.282184
4 Australia 2018 90.000000 79813.73387 2.883045
Why do I get KeyError on Country
when I use the following function?
series['Country'] = label_encoder.fit_transform(series['Country'])
I used sep=','
when I read the dataset.
答案1
得分: 0
KeyError 表示DataFrame中不存在名为 'Country' 的列。这可能是因为DataFrame中根本没有这一列。
请确保您要操作的DataFrame(您称之为 'series')确实具有名为 'Country' 的列。您可以使用以下命令检查DataFrame的列名:
print(series.columns)
如果在该命令的输出中找不到 'Country',那么您需要确定正确的列名并在代码中使用它。
没有关于CSV文件或DataFrame格式的更多信息,很难提供更精确的答案。
英文:
The KeyError means that the column 'Country' is not in your DataFrame. This might be caused that the column does not exist at all in your DataFrame.
Please ensure that the DataFrame you are trying to operate on (which you're calling 'series') actually has a column named 'Country'. You can check the column names of your DataFrame with the following command:
print(series.columns)
If 'Country' is not in the output of that command, then you need to determine the correct column name and use that in your code.
Without more information about the format of your CSV file or DataFrame, it's difficult to give a more precise answer.
答案2
得分: 0
看起来你有一些多余的空格("Country "没有正确对齐)。
用df.columns = list(map(str.strip, df.columns))
进行清理,并将df替换为你的数据框名称。
英文:
I looks like you have some excess whitespaces (the "Country " is not right aligned).
For cleaning use df.columns = list(map(str.strip, df.columns))
and replace df with the name of your dataframe.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论