Pandas에서 관계형 API 사용하기
Pandas에서 관계형 API 사용하기 (Relational API on Pandas)
DuckDB는 쿼리 연산을 이어 붙일 수 있는 **관계형 API(relational API)**를 제공해요. 이 연산들은 **지연 평가(lazily evaluated)**되므로, DuckDB가 실행을 최적화할 수 있어요. Pandas DataFrame, DuckDB 테이블·뷰(Caribou·Parquet 등 DuckDB가 읽을 수 있는 어떤 저장 형식이든 가리킬 수 있어요)를 대상으로 연산할 수 있죠.
여기서는 Pandas DataFrame에서 읽어 DataFrame으로 반환하는 간단한 예시를 볼게요.
import duckdb
import pandas
# connect to an in-memory database
con = duckdb.connect()
input_df = pandas.DataFrame.from_dict({'i': [1, 2, 3, 4],
'j': ["one", "two", "three", "four"]})
# create a DuckDB relation from a dataframe
rel = con.from_df(input_df)
# chain together relational operators (this is a lazy operation, so the operations are not yet executed)
# equivalent to: SELECT i, j, i*2 AS two_i FROM input_df WHERE i >= 2 ORDER BY i DESC LIMIT 2
transformed_rel = rel.filter('i >= 2').project('i, j, i*2 AS two_i').order('i DESC').limit(2)
# trigger execution by requesting .df() of the relation
# .df() could have been added to the end of the chain above - it was separated for clarity
output_df = transformed_rel.df()
출처: 공식문서
관계형 연산자는 행을 그룹핑하고, 집계하고, 값의 고유 조합을 찾고, 조인하고, 합치는(union) 일까지 할 수 있어요. 나아가 연산 결과를 DuckDB 테이블에 바로 넣거나 CSV로 쓸 수도 있어요.
- 추가 예시: duckdb-python.py
DuckDBPyRelation클래스의 사용 가능한 관계형 메서드: Python API 레퍼런스
더 알아보기 (Learn more)
- DuckDB와 Python 사이의 데이터 변환 전반은 Python 데이터 수집 문서에서 확인하세요.