본문 바로가기
목차
Python/pandas

[Pandas] Index 지정 관련 메서드 : reset_index, set_index

by ds31x 2023. 9. 20.
728x90
반응형

DataFrame 인스턴스에서 index를 새로 만들거나 다른 columns 를 index로 지정하는데 사용된다.

https://www.geeksforgeeks.org/pandas/python-pandas-dataframe-reset_index/


reset_index

DataFrame 인스턴스에서 기존 index 대신하는 새로운 index를 만든다.

  • drop 파라메터의 값을
    • True로 지정한 경우, 기존의 index 는 삭제됨 (default는 False임) :
    • False인 경우, 이전의 index가 column으로 추가됨.
  • inplace 파라메터의 값을
    • True로 지정한 경우, 기존의 객체를 변경한다.
    • default는 False임.

set_index

DataFrame 인스턴스에서 특정 column을 index로 지정한다.

  • keys 파라메터의 값으로 새롭게 index로 지정할 columns의 이름들을 지정한다.
  • drop 파라메터는 새롭게 index로 지정된 column을 현재 DataFrame에서 column에서 제거할지를 지정함. (default는 True임)
  • append 파라메터는 기존의 index를 column으로 새로 추가할지를 지정함 (default는 False임)
  • inplace는 현재 원본인 기존 DataFrame 인스턴스를 변경할지를 지정함 (default는 False임)

Examples

다음은 Test할 DataFrame 인스턴스를 생성하는 code snippet임.

import pandas as pd

test_df = pd.DataFrame(
    [
        [100, 'a', 'ㄱ'],
        [200, 'b', 'ㄴ'],
        [300, 'c', 'ㄷ'],
    ],
    columns=['c0', 'c1', 'c2']
)
test_df


다음을 수행하면 새로운 index가 추가되고 기존의 index를 columns 로 추가됨.

new_df = test_df.reset_index()
new_df


다음을 수행하면 새로운 index가 추가되고 기존의 index를 제거함. (이 경우 기존 DataFrame 인스턴스와 같음.)

new_df = test_df.reset_index(drop='True') #기존 index가 column으로 추가되지 않음.
new_df


다음을 수행하면 새로운 index로 column c2가 추가되고 c2를 columns에서 제거함.

new_df = test_df.set_index('c2')
new_df


다음을 수행하면 새로운 index로 c1c2의 조합이 추가되고 c1c2를 columns에 남겨둠.

new_df = test_df.set_index(['c1','c2'], drop=False)
new_df


https://gist.github.com/dsaint31x/dcbc86cbf6d2c3552c207be0fab553d9

 

py_pandas_index.ipynb

py_pandas_index.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

728x90