데이터 사이언스/데이터 분석

<예제로 보는 Pandas> 03. Index

수학과인데 공대생 2023. 7. 10. 21:36
728x90

Index

데이터에 접근할 수 있는 주소 값

 

지난 포스팅과 같은 예제를 활용하겠습니다.

https://math-love.tistory.com/17

 

<예제로 보는 Pandas> 02. DataFrame

DataFrame 2차원 데이터 (Series 들의 모음) Series와 2차원 데이터에 대한 내용은 이전 포스팅을 참고해 주시기 바랍니다. https://math-love.tistory.com/16 01. Series Pandas란? pandas란 파이썬에서 사용하는 데이터

math-love.tistory.com

 

지난 포스팅과 마찬가지로 index를 부여해보겠습니다.

import pandas as pd
data = {
    '이름' : ['홍길동', '김태희', '아이유', '손흥민', '김신욱'],
    '키' : [180, 163, 165, 187, 200],
    '국어' : [90, 40, 80, 40, 15],
    '수학' : [100, 50, 70, 70, 10],
    '영어' : [85, 35, 75, 60, 20],
    '직업' : ['Thief', 'actress', 'Singer', 'Football Player', 'Football Player']    
}
data
df = pd.DataFrame(data, index = ['1번', '2번', '3번', '4번', '5번'])
df

 

index만을 array로 받아보겠습니다.

df.index

 

 

Index 이름 설정

index를 설정하는 것까지 알아봤습니다.

index도 다른 column처럼 이름을 붙여줄 수는 없을까요?

 

-> code : df.index.name = 'name'

df.index.name = '학급번호'
df

이제 index에도 다른 열처럼 이름을 붙여주었습니다.

 

 

Index 초기화

이제 index를 초기화 해보겠습니다.

 

-> code : df.reset_index()

df.reset_index()

index가 초기화 된 것을 확인할 수 있습니다.

그런데 학급번호로 설정했던 index가 그대로 남아있습니다.

학급번호 열을 지우고 index를 초기화 하려면 추가적인 코드입력이 필요로 합니다.

 

-> code : df.reset_index(drop = True)

df.reset_index(drop = True) # 원래 쓰던 index를 dataframe에서 삭제

drop = True는 원래 사용하던 index를 drop(삭제)하라는 것입니다.

원래 사용하던 index가 dataframe에서 삭제 되었습니다.

 

 

*inplace*

이제 index를 reset 했으니 아마 print(df)를 입력하면 reset된 index를 볼 수 있을 것 같습니다.

확인해볼까요?

df

reset을 했음에도 불구하고 index설정이 그대로인 것 같습니다.

이럴때 사용하는 parmeter가 inplace입니다.

 

-> code : df.reset_index(drop = True, inplace = True)

df.reset_index(drop = True, inplace = True)
df

inplace = True로 하게 되면 기존 데이터프레임에 변경된 설정으로 덮어씌어집니다.

 

 

Index 설정

index를 기존 column의 것으로 설정할 수는 없을까요?

가능합니다.

df.set_index('이름', inplace = True)
df

 

 

Index 정렬

index를 오름차순, 내림차순으로 정렬할 수도 있습니다.

 

오름차순

-> code : df.sort_index()

df.sort_index()

 

내림차순

-> code : df.sort_index(ascending = False)

df.sort_index(ascending = False)

 

728x90