PY Function in Excel: Run Python Inside Excel

PY Function in Excel: Run Python Inside Excel 1
⏱ 1 min readUpdated 5 October 2026

AILevel: ExpertAvailable in: Excel 365 / 2021+

In this article
  1. Syntax
  2. Examples
  3. Example 1
  4. PY in practice
  5. Where you will use it
  6. Worked example
  7. Mistakes people make
  8. Related functions

PY (Python in Excel, 2023) runs Python code (pandas, matplotlib and more) in Microsoft’s cloud and returns the result to a cell. You don’t type =PY directly: type =PY( or press Ctrl+Alt+Shift+P to start a Python cell.

Advertisement

Syntax

=PY(python_code, return_type)
Argument What it means
python_code Python, e.g. xl(“A1:C100”, headers=True).describe()
return_type 0 = Excel value, 1 = Python object

Examples

Example 1

=PY(...)

Result: (the mean of the Sales column). See the worked example table below for more cases.

PY in practice

Where you will use it

  • pandas summaries of an Excel table
  • Charts with matplotlib/seaborn
  • Statistics Excel lacks (regression diagnostics, clustering)

Worked example

PythonFormulaResult
df = xl("A1:C100", headers=True); df["Sales"].mean()=PY(...)(the mean of the Sales column)

Not calculated here: PY needs the latest Microsoft 365 with Python in Excel enabled. The result shown is what it returns.

Mistakes people make

MistakeWhat to do instead
Expecting local files or internetPython in Excel runs in a sandbox in the cloud with no file or web access
Recalculation timePython cells are slower; set Calculation to manual for big models

LAMBDA

📚 Part of the free Excel course: Beginner → Expert · Try it in the Formula Lab or ask the AI Helper.

Advertisement
✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *