Python & AI

Python in Excel: What It Is and How to Use It

Python in Excel explained: how the =PY function and xl() work, Python objects vs Excel values, practical pandas examples, availability and key limitations.

By DashCore Hub Editorial TeamUpdated 8 min read

Python in Excel is a Microsoft 365 feature that lets you type Python code directly into a cell with the =PY function and use pandas, Matplotlib and other popular libraries on your worksheet data, without installing Python on your computer. The code runs in the Microsoft Cloud and returns the result to the grid as a value, a table or a chart. It is a practical bridge for Excel users who want Python's analysis power while staying inside the workbook their team already uses.

What Python in Excel is (and isn't)

Python in Excel adds a new kind of cell. Instead of a regular formula, the cell holds Python code that can read ranges and tables from your workbook. Key points to understand before you start:

  • It runs in the cloud, not on your PC. Microsoft executes the code in an isolated cloud environment with a curated set of libraries provided through Anaconda, so you need an internet connection.
  • Data comes from the workbook. Your Python code reads data from cells, tables, names and Power Query connections using the xl() function. Functions such as pd.read_csv or pd.read_excel are not meant to load outside files here; bring external data in with Power Query (Get & Transform) first.
  • It is not a full Python IDE. You cannot install any package you like or run long background jobs. For full flexibility, a local setup is still the right choice; see Python for Data Analysis: Where to Start.

Who can use it: availability and licensing

Availability depends on your Microsoft 365 plan, your platform and your update channel, and Microsoft has expanded it in stages. At the time of writing, Microsoft's support pages list Excel for Windows, Excel for Mac and Excel on the web as supported, while the mobile apps can open workbooks with Python cells but cannot recalculate them. A qualifying Microsoft 365 subscription includes Python in Excel, and an optional paid add-on offers premium compute (faster calculation) and extra recalculation modes.

Because plans, channels and prices change, confirm the details on Microsoft's official "Python in Excel availability" page and its pricing page before you rely on the feature for a team rollout. If you do not see Insert Python on the Formulas tab, your account, platform or update channel may not have it yet.

Your first Python formula, step by step

  1. Convert your data to an Excel Table (select it and press Ctrl+T) and give it a clear name such as Sales on the Table Design tab.
  2. Select an empty cell and choose Formulas > Insert Python, or type =PY( in the cell. You can also press Ctrl+Alt+Shift+P.
  3. Type your code in the cell or formula bar. In a Python cell, pressing Enter adds a new line.
  4. Press Ctrl+Enter to run (commit) the code.
  5. Choose how to show the result: as a Python object or as an Excel value (more on this below).

Here is a first example that reads the table and summarizes revenue by region:

df = xl("Sales[#All]", headers=True)
df["Revenue"] = df["Units"] * df["Price"]
df.groupby("Region")["Revenue"].sum().sort_values(ascending=False)

The last line of the cell is what gets returned. xl("Sales[#All]", headers=True) loads the entire table, including the header row, into a pandas DataFrame. You can also reference plain ranges, for example xl("A1:D200", headers=True), but tables are safer because they grow automatically when you add rows.

Python objects vs Excel values

Every Python cell can return its result in one of two ways. Switch between them from the Python output menu next to the formula bar, by right-clicking the cell, or with Ctrl+Alt+Shift+M.

Output typeWhat you seeUse it when
Python objectA card icon with the object type (for example DataFrame); click it to previewYou will reuse the result in later Python cells
Excel valueThe result spilled into the grid as normal numbers and textYou want regular formulas, charts or conditional formatting to use the result
Tip: Python cells calculate in row-major order: left to right across a row, then down to the next row, and sheet by sheet in workbook order. Put your data-loading cell at the top-left of a dedicated "Python" sheet, and place cells that depend on it below or to the right. A variable must be defined in an earlier cell before another cell can use it.

Practical examples for analysts

Clean a messy column

df = xl("Sales[#All]", headers=True)
df["Customer"] = df["Customer"].str.strip().str.title()
df = df.drop_duplicates(subset=["OrderID"])
df

Quick descriptive statistics

df = xl("Sales[#All]", headers=True)
df[["Units", "Price"]].describe()

Returned as an Excel value, this gives count, mean, standard deviation, minimum, quartiles and maximum in one spill range.

A chart inside a cell

import matplotlib.pyplot as plt

df = xl("Sales[#All]", headers=True)
monthly = df.groupby("Month")["Units"].sum()
fig, ax = plt.subplots()
monthly.plot(kind="bar", ax=ax, title="Units by month")
fig

The chart appears as an image object in the cell. You can open it in a larger view or place it over the grid as a picture. For more chart styles, read Charts in Python: Matplotlib vs Plotly.

Common libraries such as pandas, NumPy, Matplotlib and seaborn are available out of the box; Microsoft documents the full list and the default imports in its "Open-source libraries and Python in Excel" and initialization settings articles.

Python in Excel vs regular Excel formulas

You do not need Python for everything. Dynamic array functions such as FILTER, SORT and UNIQUE handle many tasks elegantly; see Excel Dynamic Arrays. Python in Excel is most useful when you need:

  • Statistical analysis beyond built-in functions (regression with statsmodels, correlations, distributions).
  • Text cleanup with regular expressions.
  • Chart types Excel does not offer natively, such as seaborn heatmaps or pair plots.
  • Reusable, readable logic where a formula would become an unreadable nest of IFs.

Keep in mind that recipients need a supported Excel version to recalculate Python cells, although they can still see the last calculated results.

Limitations and good practices

  • Internet required: errors such as #CONNECT! usually mean the cloud service could not be reached.
  • Performance: large workbooks with many Python cells can feel slow. Switch to manual or partial calculation and press F9 when you are ready to recalculate.
  • Error codes: #PYTHON! means your code raised an error; open the diagnostics pane to read the message. #BUSY! means the calculation is still running.
  • Data governance: your organization's administrators can control the feature, and Microsoft documents how data is handled in its "Data security and Python in Excel" article. Review it before using sensitive data.
  • Documentation: add comments in your code (lines starting with #) so colleagues understand what each cell does.
AI shortcut: Describe your table to an AI assistant and ask for Python in Excel code specifically: "I have an Excel table named Sales with columns OrderDate, Region, Product, Units, Price. Write Python in Excel code using xl() that returns the top 3 products by revenue for each region as a DataFrame. Do not use read_csv." Mentioning xl() and the table name keeps the answer compatible with Excel's environment.

Next steps

Check whether Insert Python appears on your Formulas tab, convert one dataset into a named table and recreate a pivot table with groupby. Then try a chart and a quick describe(). When you outgrow the cell-based workflow, move the same pandas skills to a notebook with our pandas tutorial for Excel users.

Watch: video lessons

Getting Started with Python in Excel (2025) | Beginner Guide | TheCodeSpiceby TheCodeSpice · Watch on YouTube ↗
¡Aprende Python en Excel desde CERO! 🚀 El Tutorial Más Fácil y Rápido para Principiantesby El Inge Francisco · Watch on YouTube ↗Video in Spanish.

Frequently asked questions

Do I need to install Python to use Python in Excel?

No. The code runs in the Microsoft Cloud with libraries provided through Anaconda, so nothing needs to be installed locally. You do need an internet connection and a qualifying Microsoft 365 subscription.

Can Python in Excel read CSV files or connect to the internet?

Your Python code works with data already in the workbook, read through the xl() function. To use external files or databases, import them with Power Query first and then reference the result with xl().

Is Python in Excel free?

It is included with qualifying Microsoft 365 subscriptions, and Microsoft sells an optional add-on with premium compute and extra calculation modes. Plans and prices change, so check Microsoft's official availability and pricing pages.

Can I install extra Python packages?

Python in Excel provides a curated set of libraries through Anaconda rather than letting you install any package. Microsoft's open-source libraries article lists what is available.

Learning with the Academy?
Mark this lesson complete to track your rank progress.
Take the quiz