강의

멘토링

커뮤니티

Inflearn Community Q&A

dlwjd109415289's profile image
dlwjd109415289

asked

Python programming that even beginners can learn in one breath

Clean and extract data, then visualize it

혹시 new data에서 인덱싱 새롭게 set할때, 인덱싱하려는 컬럼의 key값이 없으면 어떻게 할까요?

Written on

·

299

1

안녕하세요. 강의 정말 잘 듣고 있습니다. 

강의 내용 중, new data에 set_index('월', inplace-=True)로 새롭게 인덱싱을 정리하는 부분에서 질문이 있습니다. 

만약 원래 데이터에서 인덱스값이 들어가있는 컬럼명, 즉 key값이 없을 경우에는 어떻게 인덱스를 정리할수 있을까요? 

인프런 신규강의 (무료)python

Answer 2

0

pythonmento님의 프로필 이미지
pythonmento
Instructor

존재하지 않는 컬럼을 넣으면 다음과 같이 KeyError가 발생합니다.

>>> df = pd.DataFrame({'month': [1, 4, 7, 10],
                   'year': [2012, 2014, 2013, 2014],
                   'sale': [55, 40, 84, 31]})
>>> df
   month  year  sale
0      1  2012    55
1      4  2014    40
2      7  2013    84
3     10  2014    31
>>> df.set_index('wow')
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    df.set_index('wow')
  File "D:\python37\lib\site-packages\pandas\core\frame.py", line 4303, in set_index
    raise KeyError(f"None of {missing} are in the columns")
KeyError: "None of ['wow'] are in the columns"

0

pythonmento님의 프로필 이미지
pythonmento
Instructor

좋은 질문 감사드립니다. 데이터 예시를 간략하게 들어주시면 테스트해서 답변 드리겠습니다!

dlwjd109415289's profile image
dlwjd109415289

asked

Ask a question