σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
Polars skill›Module 3 · Interop and the query engine›Topic 3.1·~40 minIntermediate

Polars with pandas and Arrow

Skill positionModule 3 of 3 · Topic 1 of 5
3.1 Polars with pandas and Arrow
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02To pandas and back
  3. 03Arrow: the shared memory format
  4. 04NumPy: a view you must not write into
  5. 05What the tasks ask

No tool does everything, so a good tool talks to the others. Polars hands a table to pandas for a library that expects it, to Arrow for a file format or another process, and to NumPy for a model, then takes the result back, usually without copying the numbers.

01

The idea in plain words

Where we are. The first six topics stayed inside Polars. This one crosses the border and comes back. pandas is the language of most of Python's data libraries, so it matters how its index and dates map onto Polars columns. Arrow is the shared memory format from the Arrow skill. NumPy arrays are what numerical code and models take, and there a read-only detail bites.

DefinitionZero-copy

Handing data to another tool by sharing the same memory instead of duplicating it. It is fast and uses no extra memory, but the receiver is looking at the owner's bytes, so it must not change them.

02

To pandas and back

to_pandas() returns a pandas DataFrame. pandas likes its dates in the index, so set_index("date") finishes the job. Coming back, Polars has no index: reset_index() turns it into a column again before pl.from_pandas. One surprise: a pandas datetime64 column arrives as a Polars Datetime, with a time of day, so cast it to pl.Date if you mean days.

main.pyPython
# Out to pandas (dates become the index) and back (the index becomes a column again)prices = to_pandas_prices(bars, "KO")print(type(prices).__name__, "| index:", prices.index.name, "|", len(prices), "rows | 5-day mean close:", round(prices["close"].rolling(5).mean().iloc[-1], 2))back = from_pandas_prices(prices)print(back.columns, "| date type:", back.schema["date"].base_type())
DataFrame | index: date | 6699 rows | 5-day mean close: 89.55
['date', 'open', 'high', 'low', 'close', 'volume', 'ret'] | date type: Date
main.pyPython
# Without the cast the dates come back as Datetime values, with a time of dayraw = pl.from_pandas(prices.reset_index())print(raw.schema["date"].base_type(), "->", back.schema["date"].base_type())
Datetime -> Date
03

Arrow: the shared memory format

Polars stores its columns in the Arrow layout, so to_arrow() mostly re-labels memory instead of copying it, and pl.from_arrow does the same on the way back. In between you may use anything that speaks Arrow, such as the pyarrow.compute functions from the Arrow skill. That is how a Polars table crosses into DuckDB, Parquet writers and other processes cheaply.

main.pyPython
# Filter in Arrow with pyarrow.compute, then come back to Polarsbig = big_volume_arrow(bars, 900_000_000)table = bars.to_arrow()print(type(table).__name__, table.num_rows, "rows |", type(big).__name__, big.height, "rows with volume >= 900 million")print(big.group_by("symbol").len().sort("symbol").rows())
Table 33493 rows | DataFrame 846 rows with volume >= 900 million
[('AAPL', 846)]
04

NumPy: a view you must not write into

series.to_numpy() of a numeric column with no nulls shares Polars' own memory, so Polars marks the array read-only: writing into it would silently rewrite the frame. When your code needs to change values, such as clipping or standardising in place, make an explicit .copy(). The copy costs one pass of memory and buys you an array that is yours.

main.pyPython
# The view is read-only; the copy can be changed and leaves the frame aloneview = bars["close"].to_numpy()mine = writable_copy(bars, "close")mine[0] = 0.0print("view writable:", view.flags.writeable, "| copy writable:", mine.flags.writeable)print("frame still starts with", bars["close"][0], "after setting the copy to", mine[0])
view writable: False | copy writable: True
frame still starts with 0.83826 after setting the copy to 0.0
Convert at the edge, not in the middle

Every crossing has a cost and a type quirk: index to column, Date to Datetime, view to copy. Keep the pipeline in Polars and convert once, at the point where another library really needs its own type. A loop that bounces between pandas and Polars on every step loses most of what Polars gives you.

05

What the tasks ask

  1. 1
    `to_pandas_prices` and `from_pandas_prices`Filter, select, to_pandas().set_index("date"); back: pl.from_pandas(prices.reset_index()), cast date to pl.Date, add pct_change() as ret.
  2. 2
    `big_volume_arrow` and `writable_copy`to_arrow(), pc.greater_equal(table["volume"], minimum), table.filter(mask), pl.from_arrow; bars[name].to_numpy().copy().

Key takeaways

  • Index becomes column reset_index() before from_pandas, and mind Date versus Datetime.
  • Arrow is shared memory to_arrow() and pl.from_arrow cross cheaply to anything that speaks Arrow.
  • Copy before you write A NumPy view of a column is read-only. Next: the lazy API and query plans.
Quick check
to_numpy() on a price column gives an array, and arr[0] = 0 raises an error saying the array is read-only. What is the right fix?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Hand a symbol to pandas: to_pandas_prices25 pts
  • Bring pandas back: from_pandas_prices25 pts
  • Filter in Arrow: big_volume_arrow25 pts
  • A NumPy array you can change: writable_copy25 pts
Explorer · lab-7-1
▾ lab-7-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-7-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-7-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes