Wauvel

Excel like a finance pro.

← The library

Python & AI function

PY

Runs Python code in a cell using Python in Excel, returning either a Python object or an Excel value.

OccasionalDifficulty 1550 · AdvancedUsage rank #231 of 520
Practice · 3 questions →

When to use it

Runs Python inside a cell using Python in Excel. Type =PY( to enter Python mode; reference cells with xl(). The second argument chooses whether the result comes back as an Excel value or stays a Python object.

The shape of it

Syntax
=PY(python_code, return_type)

Worked examples

  • A simple calculation

    =PY("xl(\"B2\") * 2", 1) 20

    B2 is 10. Return type 1 puts the value in the grid.

  • A library call

    =PY("import statistics; statistics.median(xl(\"A1:A10\", headers=False)[0])", 1) 52,000

    A library call over a range.

  • pandas over a table

    =PY("xl(\"Table1[#All]\", headers=True).describe()", 1) summary statistics table

    pandas describe() on a table, spilled.

Worth knowing

  • Type =PY( or press Ctrl+Alt+Shift+P to open a Python cell. Reference ranges with xl("A1:B10").
  • Ctrl+Alt+Shift+P opens a Python cell directly.
  • Return type 0 keeps a DataFrame as a Python object for another PY cell to use.
  • Code runs in the Microsoft cloud, so private data leaves the machine.

Where it goes wrong

  • #PYTHON! with a message for runtime errors; check the diagnostics pane.
  • Requires a Microsoft 365 plan with Python in Excel and an internet connection.

Related

Learn the moves here — or let Wauvel run them on your numbers.

Meet your AI CFO →

One CFO-grade Excel tip a week

A short, practical email for finance operators — functions, shortcuts, and the moves that save an afternoon. Free, unsubscribe anytime.