안녕하세요. pandas 값 변경 관련 문의입니다. KeyError

조회수 8996회
csv = pd.read_csv("bmi.csv")

csv.head()

위와같은 코드를 만들어 아래와 같은 dataframe을 만들었습니다

   height       weight      label

0       195     64      thin

1   165         58      normal

2   130         37      normal

3   137         53      fat

4   120     40      fat

여기서 height 값과 weight값을 변경하고 싶어 다음과 같이 코드를 만들었습니다.

csv["height"] = csv["height"]/200
csv["weight"] = csv["weight"]/100
print(csv["weight"])
bclass = {"thin": [1, 0, 0], "normal" : [0, 1, 0], "fat" : [0, 0, 1]}
csv["label_pat"] = csv["label"].apply(lambda x : np.array(bclass[x]))

그 이후 아래와 같은 에러때문에 진행이 안되는데 혹시 아시는 분 계신가요.

KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2656             try:
-> 2657                 return self._engine.get_loc(key)
   2658             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'weight'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-9-9d3d4ac66f19> in <module>
      1 csv["height"] = csv["height"]/200
----> 2 csv["weight"] = csv["weight"]/100
      3 print(csv["weight"])
      4 bclass = {"thin": [1, 0, 0], "normal" : [0, 1, 0], "fat" : [0, 0, 1]}
      5 csv["label_pat"] = csv["label"].apply(lambda x : np.array(bclass[x]))

~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2925             if self.columns.nlevels > 1:
   2926                 return self._getitem_multilevel(key)
-> 2927             indexer = self.columns.get_loc(key)
   2928             if is_integer(indexer):
   2929                 indexer = [indexer]

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2657                 return self._engine.get_loc(key)
   2658             except KeyError:
-> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2661         if indexer.ndim > 1 or indexer.size > 1:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'weight'

weight 값 때문에 안되는데 뭘까요. 고수님들 답을 알려주세요.

1 답변

  • KeyError 는 csv['weight'] 에서 납니다. 에러 메시지만 보면 csv 란 데이터프레임에서 'weight'란 Key 에 접근할 수 없다는 거고, 'weight' 란 이름의 컬럼이 없을 때 저런 에러가 발생하게 됩니다.

    그런데, 데이터프레임을 .head() 로 표시해 봤을 때에는 weight란 이름의 컬럼이 있는 것처럼 보였단 말이죠. 컬럼 이름 양쪽에 빈칸이나 인쇄할 수 없는 문자가 포함되어 있지는 않은지 확인해 봐야 할 것 같습니다.

    print(csv.columns)
    

    를 해 보면, 컬럼명들이 따옴표와 함께 표시됩니다. 빈칸이 있는지 확인해 보시고.

    더 명확하게 확인하려면,

    print('weight' in csv.clumns)
    

    True가 나오는지 확인해 보시기 바랍니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)