Как мне изменить индекс в CSV-файле с помощью pandas на python?

#python #pandas #keyerror

#python #pandas #ошибка ключа

Вопрос:

Я пытаюсь сделать «ID» в качестве индекса, он выдает ошибку, упомянутую ниже, и изображение:

введите описание изображения здесь

 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:Userssharathkumar.chattarAppDataLocalProgramsPythonPython36-32libsite-packagespandascoreindexesbase.py", line 2656, in get_loc
    return self._engine.get_loc(key)
  File "pandas_libsindex.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas_libsindex.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas_libshashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas_libshashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'ID'
  

Комментарии:

1. Можете ли вы добавить выходные данные obj.columns. tolist() здесь?

2. что такое print(obj.columns) ? работает ли это после obj.columns = obj.columns.str.strip() ..??

3. Да, «ID», похоже, отсутствует в obj.columns

Ответ №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