[Pandas] between / 다중 조건
Pandas between, Pandas 다중 조건, pandas combining filters
정의
.between(left, right) 는 SQL BETWEEN 과 같이 두 값 사이 인지 검사하는 Series 메서드. 다중 조건 조합은 &, |, ~ 비트연산자로.
between 기본
df[df['age'].between(20, 30)] # 20 ≤ age ≤ 30 (양쪽 inclusive)
df[df['age'].between(20, 30, inclusive='left')] # [20, 30)
df[df['age'].between(20, 30, inclusive='right')] # (20, 30]
df[df['age'].between(20, 30, inclusive='neither')] # (20, 30)
python
import pandas as pd
df = pd.DataFrame({'name': ['A', 'B', 'C', 'D'], 'age': [18, 25, 30, 45]})
print(df[df['age'].between(20, 30)])
print('---')
print(df[df['age'].between(20, 30, inclusive='neither')]) 결과
name age
1 B 25
2 C 30
---
name age
1 B 25다중 조건 조합
# AND
df[(df['age'] > 25) & (df['city'] == 'Seoul')]
# OR
df[(df['city'] == 'Seoul') | (df['city'] == 'Busan')]
# NOT
df[~(df['city'] == 'Seoul')]
# 복잡한 조합
df[((df['age'] > 25) & (df['city'] == 'Seoul')) | (df['salary'] > 5000)]
IMPORTANT
각 조건은 괄호로 감싼다. &, | 의 우선순위가 비교 연산자보다 높아서 괄호 없으면 잘못 평가된다.
가독성을 위한 변수 분리
긴 조건은 변수로 쪼개라.
is_adult = df['age'] >= 18
is_capital = df['city'].isin(['Seoul', 'Tokyo', 'Beijing'])
has_premium = df['plan'] == 'premium'
df[is_adult & is_capital & has_premium]
Pandas query 도 가독성 대안.
df.query("age >= 18 and city in ['Seoul', 'Tokyo', 'Beijing'] and plan == 'premium'")
any / all
여러 조건 중 하나라도 / 모두 만족하는지를 axis 기준으로 집계.
conditions = pd.concat([
df['age'] > 30,
df['salary'] > 5000,
df['city'] == 'Seoul'
], axis=1)
df[conditions.any(axis=1)] # 하나라도 True
df[conditions.all(axis=1)] # 모두 True
함정
1. between 의 NaN 처리
df['age'].between(20, 30)
# NaN 인 행은 False
NaN 을 명시적으로 처리하려면 isna() 와 조합.
2. 문자열도 between 가능
df['name'].between('A', 'C') # 알파벳 순서로 'A' ≤ name ≤ 'C'
사전순 비교. 한글은 유니코드 순.
3. inclusive 의 string 값
pandas 1.x: inclusive=True/False, 2.x: inclusive='both' / 'left' / 'right' / 'neither'.
df['age'].between(20, 30, inclusive='both') # 권장 (명시적)
다중 조건의 성능
대규모 데이터에서 boolean mask 가 누적되는 비용. 다음 패턴이 빠를 때가 있다.
# 가장 selective 한 조건 먼저
result = df[df['rare_value'] == 'X'] # 작은 결과로 줄임
result = result[result['common'] > 100] # 그 다음 필터
Pandas query 는 numexpr 가속으로 큰 DataFrame 에서 종종 더 빠르다.
참고
이 글의 용어 (3개)
- [Pandas] Boolean Indexingpandas
- 정의 Boolean Indexing 은 True/False 의 Series 를 인덱서로 전달 해 행을 선택하는 패턴. pandas 의 가장 흔한 필터링 방법. 기본 <CodeWi…
- [Pandas] isin / isna / notnapandas
- 정의 | 메서드 | 의미 | |:---|:---| | | 각 원소가 values 안에 있는지 (boolean Series) | | | NaN/NaT/None 여부 ( 별칭) | …
- [Pandas] query / evalpandas
- 정의 - : 문자열로 boolean 표현식 을 전달해 행 필터링 - : 문자열로 계산 표현식 을 평가 의 가독성 있는 대안. query 기본 긴 조건일수록 query 가 짧고 읽…
💬 댓글