Programming

pandas dataframe에서 integer location으로 dataframe 조회하기

engyjoon 2021. 1. 22. 09:08

[준비] dataframe 생성

import pandas as pd

list_val = [
    [1, 2, 3],
    [1, 5, 6],
    [7, 8, 9],
    [10, 11, 12],
    [13, 14, 15]
]

list_col = ['col1', 'col2', 'col3']
list_idx = ['a', 'b', 'c', 'd', 'e']

df_a = pd.DataFrame(list_val, columns=list_col, index=list_idx)
df_a

※ integer location은 조회한 dataframe에서 보이지 않는다.


[방법1] row integer loaction 기준으로 dataframe 1개 조회

df_a.iloc[[0]]

※ [0] 대신 0을 입력하면 dataframe이 아니라 series가 조회된다.

※ iloc에는 index와 value를 함께 지정할 수 있다. value 생략의 명시적 표현은 아래와 같다.

df_a.iloc[[0], :]


[방법2] row integer loaction 기준으로 dataframe 여러 개 조회

df_a.iloc[[0, 3, 4]]


[방법3] row integer loaction 기준으로 dataframe 여러 개를 범위로 조회

df_a.iloc[2:5]


[응용] row/column integer location 기준으로 datafrom 여러 개를 범위로 조회

df_a.iloc[1:4, 0:2]


[참고]

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