본문 바로가기
Data Science/Pandas, Numpy

[Pandas] Reset_index, set_index 비교

by Queen2 2022. 9. 21.
728x90
반응형

pandas.DataFrame.reset_index

데이터프레임의 인덱스를 리셋하여 default index를 사용함 (멀티인덱스의 경우, 1개 이상의 인덱스를 삭제할 수 있음)

DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='', allow_duplicates=_NoDefault.no_default, names=None)

여기서 default index란, 0,1,2,3,4... 이런 식으로 숫자형의 index를 의미합니다

 

 

예시_ 아래 와 같은 df에 reset_index를 진행하면, 기존 첫 index가 컬럼이 되고 sequential index가 추가되게 됩니다

   class  max_speed
falcon    bird      389.0
parrot    bird       24.0
lion    mammal       80.5
monkey  mammal        NaN
>>> df.reset_index()
    index   class  max_speed
0  falcon    bird      389.0
1  parrot    bird       24.0
2    lion  mammal       80.5
3  monkey  mammal        NaN

 

 

추가적으로 만약에 df.reset_index(drop=True)를 표시하면 → 기존 index가 drop되게 됩니다

>>> df.reset_index(drop=True)
    class  max_speed
0    bird      389.0
1    bird       24.0
2  mammal       80.5
3  mammal        NaN

 

 

인덱스가 여러개인 MultiIndex에서도 reset_index 적용이 가능한데요

               speed species
                 max    type
class  name
bird   falcon  389.0     fly
       parrot   24.0     fly
mammal lion     80.5     run
       monkey    NaN    jump

 

이렇게 names 옵션을 리스트 형태로 제시하면  index 컬럼에 이름을 붙여줄 수 있습니다

>>> df.reset_index(names=['classes', 'names'])
  classes   names  speed species
                     max    type
0    bird  falcon  389.0     fly
1    bird  parrot   24.0     fly
2  mammal    lion   80.5     run
3  mammal  monkey    NaN    jump

 

멀티컬럼에서 여러 index중 하나만 리셋하고 싶다면 level을 사용하면 됩니다

>>> df.reset_index(level='class')
         class  speed species
                  max    type
name
falcon    bird  389.0     fly
parrot    bird   24.0     fly
lion    mammal   80.5     run
monkey  mammal    NaN    jump

 

여기서 class의 col_level은 default인 0에 가있는걸 볼 수 있는데요, 여기서 level을 바꾸고 싶다면 col_level 사용

>>> df.reset_index(level='class', col_level=1)
                speed species
         class    max    type
name
falcon    bird  389.0     fly
parrot    bird   24.0     fly
lion    mammal   80.5     run
monkey  mammal    NaN    jump

 

여기서 비어 있는 col_level 1을 채울 파라미터를 넣고 싶다면  col_fill 사용

>>> df.reset_index(level='class', col_level=1, col_fill='genus')
                genus  speed species
                class    max    type
name
falcon           bird  389.0     fly
parrot           bird   24.0     fly
lion           mammal   80.5     run
monkey         mammal    NaN    jump

 

 


이제 이와 유사한 set_index를 알아보겠습니다 :)

 

pandas.DataFrame.set_index

: 데이터프레임의 인덱스를 1개 이상의 기존 컬럼 또는 배열을 활용하여 재정의함

DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)

 

 

아래와 같은 데이트 프레임이 있을 때

>>> 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를 실행하면 이렇게 지정한 key로 index가 바뀌게 됩니다

>>> df.set_index('month')
       year  sale
month
1      2012    55
4      2014    40
7      2013    84
10     2014    31

 

set_index도 멀티 인덱스 설정이 가능합니다

>>> df.set_index(['year', 'month'])
            sale
year  month
2012  1     55
2014  4     40
2013  7     84
2014  10    31

 

흥미로웠던 점은 숫자형 index와 컬럼명 형태를 동시에 멀티인덱스로 할 수 있다는 점이었는데요

>>> df.set_index([pd.Index([1, 2, 3, 4]), 'year'])
         month  sale
   year
1  2012  1      55
2  2014  4      40
3  2013  7      84
4  2014  10     31

 

(역시 공식문서에는 배울점이 많군요 ㅎㅎㅎㅎ....)

새로 발견한 또 하나의 기능은 데이터 시리즈를 이용한 멀티 인덱싱도 가능하다는 점이었습니다!

>>> s = pd.Series([1, 2, 3, 4])
>>> df.set_index([s, s**2])
      month  year  sale
1 1       1  2012    55
2 4       4  2014    40
3 9       7  2013    84
4 16     10  2014    31

 

(코드 출처: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reset_index.html

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html)

 


차이점을 정리한다면.

Reset index는 기본적으로 숫자 index로 정리한다! 그리고 옵션이 많다

Set index는 어떤 컬럼으로 index를 바꿔라!는 느낌이  더 강한 것 같습니다

728x90
반응형

댓글