해결된 질문
작성
·
50
0
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요!
질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요
먼저 유사한 질문이 있었는지 검색해보세요
안녕하세요. 시나공과 인프런 병행하고 있는 생초보입니다. 2과목 문제에서 자꾸
train.pop 을 쓰면 해당 칼럼이 없어져서 그 이후부터는 에러만 나옵니다. (train.pop이 문제인지도 확실히 모릅니다. 챗지피티 검색해보앗습니다)
KeyError: 'Segmentation'
뭐가 문젠지 모르겠습니다 ㅠㅠ
train.shape, test.shape
train.head(3)
train.info()
train.describe()
train.describe(include='object')
test.describe(include='object')
train.isnull().sum().sum()
test.isnull().sum().sum()
target=train.pop('Segmentation')
print(train.shape, test.shape)
train = pd.get_dummies(train)
test = pd.get_dummies(test)
print(train.shape, test.shape)
KeyError Traceback (most recent call last)
/usr/local/lib/python3.11/dist-packages/pandas/core/indexes/base.py in get_loc(self, key)
3804 try:
-> 3805 return self._engine.get_loc(casted_key)
3806 except KeyError as err:
index.pyx in pandas._libs.index.IndexEngine.get_loc()
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: 'Segmentation'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
4 frames
<ipython-input-25-73fc94c13b3a> in <cell line: 0>()
15 test.isnull().sum().sum()
16
---> 17 target=train.pop('Segmentation')
18 print(train.shape, test.shape)
19 train = pd.get_dummies(train)
/usr/local/lib/python3.11/dist-packages/pandas/core/frame.py in pop(self, item)
5817 3 monkey NaN
5818 """
-> 5819 return super().pop(item=item)
5820
5821 def _replace_columnwise(
/usr/local/lib/python3.11/dist-packages/pandas/core/generic.py in pop(self, item)
945
946 def pop(self, item: Hashable) -> Series | Any:
--> 947 result = self[item]
948 del self[item]
949
/usr/local/lib/python3.11/dist-packages/pandas/core/frame.py in __getitem__(self, key)
4100 if self.columns.nlevels > 1:
4101 return self._getitem_multilevel(key)
-> 4102 indexer = self.columns.get_loc(key)
4103 if is_integer(indexer):
4104 indexer = [indexer]
/usr/local/lib/python3.11/dist-packages/pandas/core/indexes/base.py in get_loc(self, key)
3810 ):
3811 raise InvalidIndexError(key)
-> 3812 raise KeyError(key) from err
3813 except TypeError:
3814 # If we have a listlike key, _check_indexing_error will raise
KeyError: 'Segmentation'
답변 2
0
안녕하세요:) 이 경우 Segmentation 가 pop()을 통해 이미 삭제 되었는데
또 실행해서 Segmentation 컬럼이 없을 때 발생해요
데이터를 불러오는 코드부터 다시 실행한다면 아무런 문제 없이 실행 될거에요:)
0
안녕하세요, 인프런 AI 인턴입니다. 양지은님.
질문하신 내용에 대한 답변을 드리겠습니다. train.pop('Segmentation')
구문에서 발생하는 KeyError
는 해당 ‘Segmentation’이라는 컬럼이 train
데이터프레임 내에 존재하지 않을 때 발생하는 오류입니다. pop
메소드는 지정한 컬럼을 데이터프레임에서 제거하면서 반환하는데, 존재하지 않은 컬럼을 지정하면 이와 같은 오류가 나타납니다.
다음과 같은 방법으로 문제를 해결할 수 있습니다:
컬럼 존재 여부 확인하기:
train.columns
를 사용하여 train
데이터프레임에 어떤 컬럼들이 있는지 출력하여 실제로 ‘Segmentation’ 컬럼이 존재하는지 확인합니다.데이터 로드 과정 확인:
오타 확인하기:
데이터 확인:
train.head()
및 train.info()
등을 이용하여 확인하는 것도 좋은 방법입니다.유사한 문제를 다룬 답변 및 추가 정보를 원하시면, 라벨로 인코딩과 오류에 관한 질문 및 답변을 살펴보시기 바랍니다. 이 질문에서는 컬럼을 다루는 방법과 오류 해결을 위한 팁을 제공합니다.
저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다. 현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏 추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.