如何通过python中的pandas更改CSV文件中的索引?

时间:2019-03-13 18:44:10

标签: python pandas keyerror

我正在尝试将“ ID”作为索引,它会引发下面提到的错误和图像:

enter image description here

obj= pd.read_csv("Supermarkets.csv")
obj

  ID   Address       City Country           Name  Number
0    1  Ecity-1  Bangalore   India   village mart       2
1    2  Ecity-2     Mysore   India           More       3
2    3  Ecity-3    Dharwad   India     Bigg bazar       1
3    4  Ecity-4     Haveri   India     Super Mart       2
4    5  Ecity-5     Badami   India  Kirani angadi       1

obj.set_index("ID")

错误

Traceback (most recent call last):
  File "C:\Users\sharathkumar.chattar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\indexes\base.py", line 2656, in get_loc
    return self._engine.get_loc(key)
  File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'ID'

1 个答案:

答案 0 :(得分:1)

我认为问题是您在“ ID”列名称中有尾随空格。我复制了您的数据,但删去了导入时的多余空间。您会注意到列名如何正确对齐。您的ID列似乎没有,可能是因为名称中有尾随空格。其他列名称也是如此。

import pandas as pd

obj = pd.read_csv('Supermarkets.csv')
obj


   ID  Address       City Country           Name  Number
0   1  Ecity-1  Bangalore   India   village mart       2
1   2  Ecity-2     Mysore   India           More       3
2   3  Ecity-3    Dharwad   India     Bigg bazar       1
3   4  Ecity-4     Haveri   India     Super Mart       2
4   5  Ecity-5     Badami   India  Kirani angadi       1


obj.set_index("ID")


    Address       City Country           Name  Number
ID                                                   
1   Ecity-1  Bangalore   India   village mart       2
2   Ecity-2     Mysore   India           More       3
3   Ecity-3    Dharwad   India     Bigg bazar       1
4   Ecity-4     Haveri   India     Super Mart       2
5   Ecity-5     Badami   India  Kirani angadi       1

我可以复制您的相同数据表,并通过使用全名和空格来避免错误:

obj = pd.read_csv('Supermarkets_spaces.csv')
obj


   ID   Address       City Country           Name   Number 
0     1  Ecity-1  Bangalore   India   village mart        2
1     2  Ecity-2     Mysore   India           More        3
2     3  Ecity-3    Dharwad   India     Bigg bazar        1
3     4  Ecity-4     Haveri   India     Super Mart        2
4     5  Ecity-5     Badami   India  Kirani angadi        1


obj.set_index("ID  ")


     Address       City Country           Name   Number 
ID                                                      
1     Ecity-1  Bangalore   India   village mart        2
2     Ecity-2     Mysore   India           More        3
3     Ecity-3    Dharwad   India     Bigg bazar        1
4     Ecity-4     Haveri   India     Super Mart        2
5     Ecity-5     Badami   India  Kirani angadi        1