[pandas] DataFrame iloc

DataFrame.iloc

loc와 달리 iloc를 사용하면 숫자 index를 사용해서 DataFrame의 정보를 불러올 수 있다.

대부분의 예제로 다음의 data를 사용한다.

import pandas as pd
import numpy as np

data = {'이름':['이지은', '박동훈', '홍길동', '강감찬', '오해영'],
        '학과':['컴퓨터', '기계','철학', '컴퓨터', '철학'],
        '학년':[1, 2, 2, 4, 3],
        '학점':[1.5, 2.0, 3.1, 1.1, 2.7]
       }
df = pd.DataFrame(data, 
                  columns = ['학과', '이름', '학점', '학년', '등급'],
                  index = ['one', 'two', 'three', 'four', 'five'])

display(df)

원하는 행 DataFrame으로 추출하기

우리가 index를 사용해 indexing을 하면 DataFrame이 아닌 다음과 같이 Series로 return하게 된다. 이것은 fancy indexing을 사용하면 해결된다.

print(df.iloc[1])      # Series
학과     기계
## 이름    박동훈
## 학점      2
## 학년      2
## 등급    NaN
## Name: two, dtype: object
display(df.iloc[[1]])   # DataFrame

image-20200913012002630

원하는 열 DataFrame으로 추출하기

DataFrame으로 column을 추출하기 위해서는 row추출과 마찬가지로 fancy indexing 을 사용하면 된다.

display(df.loc[:,'학점'])    # Series
## # one      이지은
## two      박동훈
## three    홍길동
## four     강감찬
## five     오해영
## Name: 이름, dtype: object
display(df.loc[:,['학점']])

image-20200913012425896