Python 读取管道中的数据后获取KeyError
我在这样一个管道里阅读Python 读取管道中的数据后获取KeyError,python,python-3.x,pandas,csv,Python,Python 3.x,Pandas,Csv,我在这样一个管道里阅读 test = pd.read_csv("http://kejser.org/wp-content/uploads/2014/06/Country.csv") test.head() 这是回报 SK_Country|"Number"|"Alpha2Code"|"Alpha3Code"|"CountryName"|"TopLevelDomain" 0 1|20|"ad"|"and"|"Andorra"|".ad"
test = pd.read_csv("http://kejser.org/wp-content/uploads/2014/06/Country.csv")
test.head()
这是回报
SK_Country|"Number"|"Alpha2Code"|"Alpha3Code"|"CountryName"|"TopLevelDomain"
0 1|20|"ad"|"and"|"Andorra"|".ad"
1 2|4|"af"|"afg"|"Afghanistan"|".af"
2 3|28|"ag"|"atg"|"Antigua and Barbuda"|".ag"
3 4|660|"ai"|"aia"|"Anguilla"|".ai"
4 5|8|"al"|"alb"|"Albania"|".al"
当我尝试从中提取特定数据时,如下所示:
df = test[["Alpha3Code"]]
我得到以下错误:
KeyError:['Alpha3Code']不在索引中
我不明白哪里出了问题——我可以在打印头部时看到CSV中的值,同样,当我打开CSV时,一切看起来都很好
我试着在谷歌上搜索和阅读一些关于这个问题的帖子,并尝试了不同的方法,但似乎没有什么能解决这个恼人的问题。注意到所有内容都被塞进了一个字符串列吗?这是因为您没有将分隔列的分隔符指定给
pd.read_csv
,在本例中,分隔符必须是“|”
test = pd.read_csv("http://kejser.org/wp-content/uploads/2014/06/Country.csv",
sep='|')
test.head()
# SK_Country Number Alpha2Code Alpha3Code CountryName \
# 0 1 20 ad and Andorra
# 1 2 4 af afg Afghanistan
# 2 3 28 ag atg Antigua and Barbuda
# 3 4 660 ai aia Anguilla
# 4 5 8 al alb Albania
#
# TopLevelDomain
# 0 .ad
# 1 .af
# 2 .ag
# 3 .ai
# 4 .al
正如@chrisz在评论中指出的,您必须指定分隔符:
test = pd.read_csv("http://kejser.org/wp-content/uploads/2014/06/Country.csv",delimiter='|')
test.head()
SK_Country Number Alpha2Code Alpha3Code CountryName \
0 1 20 ad and Andorra
1 2 4 af afg Afghanistan
2 3 28 ag atg Antigua and Barbuda
3 4 660 ai aia Anguilla
4 5 8 al alb Albania
TopLevelDomain
0 .ad
1 .af
2 .ag
3 .ai
4 .al
当你阅读时,你可能需要指定一个分隔符。嘿,克里斯,谢谢你的快速回答,但是你能指定你的答案吗,我对Python是全新的,所以我不知道你的确切意思?米拉多洛的回答解释了这一点。谢谢米拉多洛,这很有意义,我不知道我需要这么做,但我需要把它分开,这很有道理。我将把你的答复记为答案。