Communitygithub.com

Polars

Python ETL, 분석, pandas 마이그레이션을 위한 고성능 DataFrame 라이브러리입니다. 표현식 기반 데이터 조작, 지연 쿼리 최적화, 병렬 실행, 스트리밍 Out-of-Core 처리, Arrow 상호 운용성, 선택적 GPU 실행을 지원합니다.

Polars란 무엇인가요?

Polars는 Apache Arrow를 기반으로 구축된 Python 및 Rust용 초고속 DataFrame 라이브러리입니다. 표현식 기반 API, 지연 평가 프레임워크, 고성능 데이터 조작 기능을 제공하여 효율적인 데이터 처리, pandas 마이그레이션, 데이터 파이프라인 최적화에 사용됩니다. 이 스킬은 Polars의 설치, 기본 사용법, 핵심 개념(표현식, 지연 평가 vs 즉시 평가), 공통 연산(선택, 필터, 열 추가, 그룹화 및 집계), 집계 및 윈도우 함수, 데이터 I/O(CSV, Parquet, JSON 등), 변환(조인, 연결, 피벗), pandas 마이그레이션 가이드, 그리고 성능 최적화 모범 사례를 다룹니다. 또한 참조 문서(`reference/` 디렉토리)를 통해 각 주제에 대한 상세한 정보를 제공하며, Claude Code, Cursor, Codex 등의 AI 에이전트에서 활용할 수 있도록 설계되었습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/polars

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Polars은(는) 무엇을 하나요?

개요

Polars는 Apache Arrow를 기반으로 구축된 Python 및 Rust용 초고속 DataFrame 라이브러리입니다. 효율적인 데이터 처리, pandas 마이그레이션, 데이터 파이프라인 최적화를 위해 Polars의 표현식 기반 API, 지연 평가 프레임워크, 고성능 데이터 조작 기능을 사용하세요.

빠른 시작

설치 및 기본 사용법

이번 리프레시 중 검증된 현재 안정적인 Polars 릴리스를 설치합니다:

uv pip install "polars==1.41.2"

필요할 때만 선택적 통합 패키지를 설치합니다:

uv pip install "polars[excel,database,fsspec,pandas,numpy]==1.41.2"

기본 DataFrame 생성 및 연산:

import polars as pl

# DataFrame 생성
df = pl.DataFrame({
    "name": ["Alice", "Bob", "Charlie"],
    "age": [25, 30, 35],
    "city": ["NY", "LA", "SF"]
})

# 열 선택
df.select("name", "age")

# 행 필터링
df.filter(pl.col("age") > 25)

# 계산된 열 추가
df.with_columns(
    age_plus_10=pl.col("age") + 10
)

핵심 개념

표현식

표현식은 Polars 연산의 기본 구성 요소입니다. 데이터에 대한 변환을 설명하며, 조합, 재사용, 최적화가 가능합니다.

주요 원칙:

  • 열을 참조하려면 pl.col("column_name")을 사용합니다.
  • 메서드를 연결하여 복잡한 변환을 구성합니다.
  • 표현식은 지연되어 컨텍스트(select, with_columns, filter, group_by) 내에서만 실행됩니다.

예제:

# 표현식 기반 계산
df.select(
    pl.col("name"),
    (pl.col("age") * 12).alias("age_in_months")
)

지연 평가 vs 즉시 평가

즉시 평가 (DataFrame): 연산이 즉시 실행됩니다.

df = pl.read_csv("file.csv")  # 즉시 읽기
result = df.filter(pl.col("age") > 25)  # 즉시 실행

지연 평가 (LazyFrame): 연산이 쿼리 계획을 구축하고, 실행 전에 최적화됩니다.

lf = pl.scan_csv("file.csv")  # 아직 읽지 않음
result = lf.filter(pl.col("age") > 25).select("name", "age")
df = result.collect()  # 최적화된 쿼리 실행

지연 평가를 사용해야 하는 경우:

  • 대용량 데이터 세트 작업 시
  • 복잡한 쿼리 파이프라인에서
  • 일부 열/행만 필요할 때
  • 성능이 중요한 경우

지연 평가의 장점:

  • 자동 쿼리 최적화
  • 조건자 푸시다운(predicate pushdown)
  • 프로젝션 푸시다운(projection pushdown)
  • 병렬 실행

자세한 개념은 references/core_concepts.md를 로드하세요.

공통 연산

Select (선택)

열을 선택하고 조작합니다:

# 특정 열 선택
df.select("name", "age")

# 표현식으로 선택
df.select(
    pl.col("name"),
    (pl.col("age") * 2).alias("double_age")
)

# 패턴과 일치하는 모든 열 선택
df.select(pl.col("^.*_id$"))

Filter (필터링)

조건에 따라 행을 필터링합니다:

# 단일 조건
df.filter(pl.col("age") > 25)

# 여러 조건 (& 사용보다 깔끔)
df.filter(
    pl.col("age") > 25,
    pl.col("city") == "NY"
)

# 복잡한 조건
df.filter(
    (pl.col("age") > 25) | (pl.col("city") == "LA")
)

With Columns (열 추가/수정)

기존 열을 유지하면서 새 열을 추가하거나 수정합니다:

# 새 열 추가
df.with_columns(
    age_plus_10=pl.col("age") + 10,
    name_upper=pl.col("name").str.to_uppercase()
)

# 병렬 계산 (모든 열이 동시에 계산됨)
df.with_columns(
    pl.col("value") * 10,
    pl.col("value") * 100,
)

Group By 및 집계

데이터를 그룹화하고 집계를 계산합니다:

# 기본 그룹화
df.group_by("city").agg(
    pl.col("age").mean().alias("avg_age"),
    pl.len().alias("count")
)

# 여러 그룹 키
df.group_by("city", "department").agg(
    pl.col("salary").sum()
)

# 조건부 집계
df.group_by("city").agg(
    (pl.col("age") > 30).sum().alias("over_30")
)

자세한 연산 패턴은 references/operations.md를 로드하세요.

집계 및 윈도우 함수

집계 함수

group_by 컨텍스트 내의 일반적인 집계 함수:

  • pl.len() - 행 개수
  • pl.col("x").sum() - 값 합계
  • pl.col("x").mean() - 평균
  • pl.col("x").min() / pl.col("x").max() - 최소/최대값
  • pl.first() / pl.last() - 첫 번째/마지막 값

over()를 이용한 윈도우 함수

행 수를 유지하면서 집계를 적용합니다:

# 각 행에 그룹 통계 추가
df.with_columns(
    avg_age_by_city=pl.col("age").mean().over("city"),
    rank_in_city=pl.col("salary").rank().over("city")
)

# 여러 그룹화 열
df.with_columns(
    group_avg=pl.col("value").mean().over("category", "region")
)

매핑 전략:

  • group_to_rows (기본값): 원래 행 순서를 유지합니다.
  • explode: 더 빠르지만 행을 함께 그룹화합니다.
  • join: 리스트 열을 생성합니다.

데이터 I/O

지원 포맷

Polars는 다음 형식의 읽기 및 쓰기를 지원합니다:

  • CSV, Parquet, JSON, Excel
  • 데이터베이스 (커넥터 사용)
  • 클라우드 스토리지 (S3, Azure, GCS)
  • Google BigQuery
  • 다중/분할 파일

일반적인 I/O 연산

CSV:

# 즉시 평가
df = pl.read_csv("file.csv")
df.write_csv("output.csv")

# 지연 평가 (대용량 파일에 권장)
lf = pl.scan_csv("file.csv")
result = lf.filter(...).select(...).collect()

Parquet (성능에 권장):

df = pl.read_parquet("file.parquet")
df.write_parquet("output.parquet")

JSON:

df = pl.read_json("file.json")
df.write_json("output.json")

포괄적인 I/O 문서는 references/io_guide.md를 로드하세요.

변환

조인

DataFrame 결합:

# 내부 조인
df1.join(df2, on="id", how="inner")

# 왼쪽 조인
df1.join(df2, on="id", how="left")

# 서로 다른 열 이름으로 조인
df1.join(df2, left_on="user_id", right_on="id")

연결

DataFrame 쌓기:

# 수직 (행 쌓기)
pl.concat([df1, df2], how="vertical")

# 수평 (열 추가)
pl.concat([df1, df2], how="horizontal")

# 대각선 (다른 스키마와의 합집합)
pl.concat([df1, df2], how="diagonal")

피벗 및 언피벗

데이터 재구성:

# 피벗 (넓은 형식)
df.pivot(on="product", values="sales", index="date")

# 언피벗 (긴 형식)
df.unpivot(index="id", on=["col1", "col2"])

자세한 변환 예제는 references/transformations.md를 로드하세요.

Pandas 마이그레이션

Polars는 더 깔끔한 API와 함께 pandas에 비해 상당한 성능 향상을 제공합니다. 주요 차이점:

개념적 차이점

  • 인덱스 없음: Polars는 정수 위치만 사용합니다.
  • 엄격한 타입: 묵시적 타입 변환이 없습니다.
  • 지연 평가: LazyFrame을 통해 사용 가능합니다.
  • 기본 병렬 처리: 연산이 자동으로 병렬화됩니다.

일반적인 연산 매핑

연산PandasPolars
열 선택df["col"]df.select("col")
필터df[df["col"] > 10]df.filter(pl.col("col") > 10)
열 추가df.assign(x=...)df.with_columns(x=...)
그룹화df.groupby("col").agg(...)df.group_by("col").agg(...)
윈도우df.groupby("col").transform(...)df.with_columns(...).over("col")

주요 구문 패턴

Pandas 순차 (느림):

df.assign(
    col_a=lambda df_: df_.value * 10,
    col_b=lambda df_: df_.value * 100
)

Polars 병렬 (빠름):

df.with_columns(
    col_a=pl.col("value") * 10,
    col_b=pl.col("value") * 100,
)

포괄적인 마이그레이션 가이드는 references/pandas_migration.md를 로드하세요.

모범 사례

성능 최적화

  1. 대용량 데이터 세트에는 지연 평가 사용:

    lf = pl.scan_csv("large.csv")  # read_csv 사용 금지
    result = lf.filter(...).select(...).collect()
    
  2. 핫 경로에서 Python 함수 사용 피하기:

    • 병렬화를 위해 표현식 API 내에 머무르기
    • 필요한 경우에만 .map_elements() 사용
    • 기본 Polars 연산 선호
  3. 매우 큰 데이터에는 스트리밍 사용:

    lf.collect(engine="streaming")
    
  4. 필요한 열만 일찍 선택:

    # 좋음: 열을 일찍 선택
    lf.select("col1", "col2").filter(...)
    
    # 나쁨: 먼저 모든 열에서 필터
    lf.filter(...).select("col1", "col2")
    
  5. 적절한 데이터 타입 사용:

    • 낮은 카디널리티 문자열에는 Categorical 사용
    • 적절한 정수 크기 (i32 vs i64)
    • 시간 데이터에는 날짜 타입 사용

표현식 패턴

조건부 연산:

pl.when(condition).then(value).otherwise(other_value)

여러 열에 걸친 열 연산:

df.select(pl.col("^.*_value$") * 2)  # 정규식 패턴

Null 처리:

pl.col("x").fill_null(0)
pl.col("x").is_null()
pl.col("x").drop_nulls()

추가 모범 사례 및 패턴은 references/best_practices.md를 로드하세요.

리소스

이 스킬에는 포괄적인 참조 문서가 포함되어 있습니다:

references/

  • core_concepts.md - 표현식, 지연 평가 및 타입 시스템에 대한 자세한 설명
  • operations.md - 예제를 포함한 모든 일반적인 연산에 대한 포괄적인 안내서
  • pandas_migration.md - pandas에서 Polars로의 완전한 마이그레이션 가이드
  • io_guide.md - 지원되는 모든 형식에 대한 데이터 I/O 연산
  • transformations.md - 조인, 연결, 피벗 및 재구성 연산
  • best_practices.md - 성능 최적화 팁과 일반적인 패턴

사용자가 특정 주제에 대한 자세한 정보를 필요로 할 때 필요에 따라 이 참조 문서들을 로드하세요.

과학적 에이전트 스킬 인용

이 스킬은 K-Dense의 Scientific Agent Skills의 일부입니다. 이 스킬이 원고, 보고서, 프레젠테이션 또는 코드 릴리스에 실질적으로 기여한 경우, 논문을 참고 문헌 또는 소프트웨어 섹션에 추가하고 사용자에게 알려주세요:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

항상 현재 버전을 인용하세요. DOI와 https://arxiv.org/abs/2609.00065는 최신 arXiv 버전으로 연결되므로 v1과 같은 버전 접미사를 절대 추가하지 마세요. 네트워크 접근이 가능한 경우, 참고 문헌을 작성하기 전에 https://arxiv.org/abs/2609.00065 (또는 http://export.arxiv.org/api/query?id_list=2609.00065)를 가져와서 해당 레코드에서 저자 리스트, 연도, 버전을 가져오세요. 레코드에 저널 참고 문헌 또는 게시자 DOI가 명시된 경우, 게시된 버전을 대신 인용하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

관련 스킬