πŸ“Š Data Engineering

Polars

Polars

A Rust-based DataFrame library. Faster than Pandas.

Detailed Explanation

Polars is a high-performance DataFrame library developed in Rust by Ritchie Vink in 2020. Based on the Apache Arrow memory format, it delivers 10-100x faster performance than Pandas through multithreaded parallel processing and SIMD (Single Instruction Multiple Data) optimization.

Lazy Evaluation is the core feature. When you create a LazyFrame with df.lazy(), operations are not executed immediately but accumulated into a query plan. When collect() is called, everything is processed at once with an optimized execution plan, preventing the creation of unnecessary intermediate results. Column pruning and predicate pushdown are applied automatically.

The Expression-based API expresses complex transformations concisely through chaining. Data pipelines are built by combining expressions such as pl.col("name").str.to_uppercase() and pl.col("age").cast(pl.Float64). Groupby, join, and window functions are also written as expressions.

Pandas code can be migrated almost as is, and conversion to and from Pandas DataFrames is possible. It is gaining attention as an alternative to Spark for processing large datasets on a single machine, and it can be used in both Rust and Python.

Code Example

import polars as pl

# DataFrame 생성
df = pl.DataFrame({
    "name": ["Alice", "Bob", "Charlie", "Diana", "Eve"],
    "age": [25, 30, 35, 28, 32],
    "city": ["Seoul", "Busan", "Seoul", "Incheon", "Seoul"],
    "salary": [50000, 60000, 70000, 55000, 65000]
})

# 파일 읽기/μ“°κΈ°
# df = pl.read_csv("data.csv")
# df = pl.read_parquet("data.parquet")
# df.write_parquet("output.parquet")

# Eager Evaluation (μ¦‰μ‹œ μ‹€ν–‰)
result = df.filter(pl.col("age") > 28).select(["name", "salary"])
print(result)

# Lazy Evaluation (μ§€μ—° μ‹€ν–‰) - ꢌμž₯
lazy_df = (
    df.lazy()
    .filter(pl.col("age") > 25)
    .with_columns([
        (pl.col("salary") * 1.1).alias("new_salary"),
        pl.col("name").str.to_uppercase().alias("name_upper")
    ])
    .group_by("city")
    .agg([
        pl.col("salary").mean().alias("avg_salary"),
        pl.col("name").count().alias("count")
    ])
    .sort("avg_salary", descending=True)
)

# collect()둜 μ‹€ν–‰
result = lazy_df.collect()
print(result)

# ν‘œν˜„μ‹ μ‘°ν•©
df_transformed = df.select([
    pl.col("name"),
    pl.col("age"),
    pl.when(pl.col("salary") > 60000)
      .then(pl.lit("High"))
      .otherwise(pl.lit("Normal"))
      .alias("salary_level"),
    (pl.col("salary") / 12).round(2).alias("monthly_salary")
])
print(df_transformed)

# Window ν•¨μˆ˜
df_with_rank = df.with_columns([
    pl.col("salary")
      .rank(descending=True)
      .over("city")
      .alias("salary_rank_in_city"),
    pl.col("salary")
      .mean()
      .over("city")
      .alias("city_avg_salary")
])
print(df_with_rank)

# Join
departments = pl.DataFrame({
    "name": ["Alice", "Bob", "Charlie"],
    "department": ["Engineering", "Sales", "Engineering"]
})

joined = df.join(departments, on="name", how="left")
print(joined)

# 슀트리밍 λͺ¨λ“œ (λŒ€μš©λŸ‰ 처리)
# lazy_df = pl.scan_parquet("huge_file.parquet")
# result = lazy_df.filter(pl.col("value") > 100).collect(streaming=True)

# Pandas λ³€ν™˜
pandas_df = df.to_pandas()
polars_df = pl.from_pandas(pandas_df)

# μ„±λŠ₯ 비ꡐ (100만 ν–‰)
import time
large_df = pl.DataFrame({
    "a": list(range(1_000_000)),
    "b": list(range(1_000_000))
})

start = time.time()
result = large_df.lazy().filter(pl.col("a") > 500000).group_by("b" ).agg(pl.col("a").sum()).collect()
print(f"Polars: {time.time() - start:.3f}s")

How It's Said in Practice

Senior: "I switched our ETL pipeline from Pandas to Polars, and the processing time dropped from 30 minutes to 2 minutes. It's thanks to Lazy mode."

Junior: "Do I have to change all my Pandas code?"

Senior: "The API is similar, so you can use about 70% of it almost as is. You just need to get used to using df.select() instead of df['col']."

Interviewer: "Please tell me about your experience with processing large-scale data."

Candidate: "I processed a 5GB CSV file using Polars' scan_csv and Lazy mode. Pandas failed due to insufficient memory, but Polars was able to process it on 16GB RAM through streaming. Query optimization was applied automatically, so it read only the necessary columns and applied filter conditions at the file scan stage, minimizing I/O."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Reviewer: "Use the pattern of starting with lazy() and ending with collect(). Eager mode misses optimization opportunities."

Developer: "What do I do when I want to check results in the middle?"

Reviewer: "You can check just a sample with head().collect(), or look at the query plan with explain()."

Cautions

Learn More