
In this article
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
| Python | Formula | Result |
|---|---|---|
| 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
| Mistake | What to do instead |
|---|---|
| Expecting local files or internet | Python in Excel runs in a sandbox in the cloud with no file or web access |
| Recalculation time | Python cells are slower; set Calculation to manual for big models |
Related functions
📚 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