잠토의 잠망경

[Pandas] 데이터 추출(행, Row)-loc 본문

공부/Python

[Pandas] 데이터 추출(행, Row)-loc

잠수함토끼 2018. 12. 17. 19:20

index 개념

DataFrame에는 2가지 index 개념이 존재한다. loc, iloc이다.

속성 설명
loc index 기준
iloc 행 번호 기준

index

형태: 숫자, 문자
특징: 추가, 삭제, 변경 가능

행번호

형태: 숫자

loc 활용

인덱스를 전달, Row Data 추출, Series

import pandas as pd

df = pd.read_csv('mushrooms.csv')

print(df.loc[2])
print(df.loc[99])
print(df.loc[-1]) # error 인덱스가 존재하지 않는 영역에 접근했기때문이다.

결과는 다음과 같다

마지막 row를 추출하는 2가지 방법

1. shape 이용

Type: Series

number_of_row = df.shape[0] # shape 속성 이용 (행,열)
last_row_index= number_of_row -1
print(df.loc[last_row_index])

2. tail 이용

Type: DataFrame

n=2 이면 두 개를 획득

print(df.tail(n=1))

참고

df.head(n=5) # == df.head()
df.tail(n=5) # == df.tail()

다중 row 추출

원하는 index를 담은 list 전달

print(df.loc[[0,99,999]]) # list
Comments