如何修复:Pandas中的KeyError
在这篇文章中,我们将讨论如何修复pandas中的KeyError。当我们试图访问我们的DataFrame中不存在的某些列/行标签时,Pandas KeyError就会发生。通常情况下,当你拼错了列/行的名字或者在列/行的名字之前或之后包含了一个不需要的空格时,就会发生这种错误。
所用数据集的链接在这里
示例
# importing pandas as pd
import pandas as pd
# using .read_csv method to import dataset
df = pd.read_csv('data.csv')
输出:
重现keyError :
# intentionally passing wrong spelling of
# the key present in dataset
df['country']
输出:
KeyError: 'country'
由于没有名为国家的列,我们得到一个KeyError。
如何修复KeyError?
我们可以简单地通过纠正键的拼写来解决这个错误。如果我们对拼写不确定,我们可以简单地打印所有列名的列表并进行交叉检查。
# printing all columns of the dataframe
print(df.columns.tolist())
输出:
['Country', 'Age', 'Salary', 'Purchased']
使用栏目的正确拼法
# printing the column 'Country'
df['Country']
输出:
0 France
1 Spain
2 Germany
3 Spain
4 Germany
5 France
6 Spain
7 France
8 Germany
9 France
Name: Country, dtype: object
如果我们想避免编译器在传递无效键时引发错误,我们可以使用df.get(‘your column’)来打印列值。如果键是无效的,则不会引发错误。
语法 :
DataFrame.get( ‘column_name’ , default = default_value_if_column_is_not_present)
# Again using incorrect spelling of the
# column name 'Country' but this time
# we will use df.get method with default
# value "no_country"
df.get('country', default="no_country")
输出:
'no_country'
但当我们使用正确的拼写时,我们将得到该列的值而不是默认值。
# printing column 'Country'
df.get('Country', default="no_country")
输出:
0 France
1 Spain
2 Germany
3 Spain
4 Germany
5 France
6 Spain
7 France
8 Germany
9 France
Name: Country, dtype: object