【问题标题】:Getting KeyError after reading in pipe-separated CSV读取管道分隔的 CSV 后出现 KeyError
【发布时间】:2018-05-20 01:30:31
【问题描述】:

我在这样的管道分隔 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"                          
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 时,一切看起来都很好。

我尝试用谷歌搜索并阅读堆栈上有关此问题的一些帖子,并尝试了不同的方法,但似乎没有任何方法可以解决这个烦人的问题。

【问题讨论】:

  • 读入时可能需要指定分隔符。
  • 嗨,克里斯,谢谢你的快速回答,但你能具体说明一下吗,我是 Python 新手,所以我不知道你的意思是什么?
  • Miradulo 的回答解释了这一点。

标签: python python-3.x pandas csv


【解决方案1】:

注意所有东西是如何被塞进一个字符串列的?这是因为您没有将分隔列的分隔符指定为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 

【讨论】:

  • 谢谢 miradulo,这是有道理的,我不知道我需要这样做,但我需要将其拆分是完全有道理的。我会将您的回复标记为答案。
【解决方案2】:

正如@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  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2022-01-24
    • 1970-01-01
    • 2020-06-23
    • 2018-04-01
    • 2020-12-15
    相关资源
    最近更新 更多