Python

Pandas : 데이터 필터링하기 #1 (행 단위 데이터 추출)

Sorting 2021. 1. 29. 01:10
반응형

프레임 속에 있는 수많은 데이터 중에,

내가 원하는 대상의 데이터만 골라 새로운 프레임으로 만들고 싶다.

(마치 DB에서 where 절을 지정하여 쿼리를 날리듯)

 

위와 같은 동작은 판다스에서는 loc 프로퍼티로 수행할 수 있다.

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html

 

pandas.DataFrame.loc — pandas 1.2.1 documentation

A slice object with labels, e.g. 'a':'f'. Warning Note that contrary to usual python slices, both the start and the stop are included

pandas.pydata.org

내가 필요해서 정리해본다.


용례

다음과 같은 데이터 프레임이 있다고 가정하자

import pandas as pd
data = [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'a'), (4, 'a'), (5, 'b'), (6, 'c')]
df = pd.DataFrame(data, columns=['id', 'name'])

df.head()

이 중에서 'name' 이 'a' 인 라인들만 모아 새로운 리스트를 만들고 싶다면 어떻게 해야할까?

 

정답은 다음과 같다.

df2 = df.loc[df['name'] == 'a']
df2.head()

다음은 특별 관리대상을 담은 targets 리스트가 있다고 가정하자.

targets = ['a', 'c']

나는 name이 targets 리스트에 포함된 라인만 모아서 새로운 데이터프레임으로 옮기고 싶다.

그럴 땐 다음과 같이 isin 을 사용하면 된다.

targets = ['a', 'c']
df3 = df.loc[df['name'].isin(targets)]
df3.head()

여러 개의 조건을 조합하려면 & 혹은 | 를 쓰면 된다.

# isin(targets) 와 동일한 결과
df3 = df.loc[(df['name'] == 'a') | (df['name'] == 'c')]
df3.head()

# isin(targets) 이고, id가 4보다 작은 데이터들
df4 = df.loc[(df['name'].isin(targets)) & (df['id'] < 4)]
df4.head()

 

 

만약, isin 이 아니라 'is not in' 이 필요한 경우(여집합)에는 다음과 같이 

조건식 앞에 ~ 를 붙여준다.

df5 = df.loc[~df['name'].isin(targets)]
df5.head()

 

반응형