Python in Excel for Beginners: The First 10 Things Worth Learning

Coding Liquids tutorial cover featuring Sagnik Bhattacharya for Python in Excel for beginners, with Python cell and analytics visuals.
Coding Liquids tutorial cover featuring Sagnik Bhattacharya for Python in Excel for beginners, with Python cell and analytics visuals.

The first things a beginner should learn in Python in Excel are entering a Python cell with =PY( and committing it with Ctrl+Enter, pulling data in with xl(), working with pandas DataFrames, and choosing Excel Value or Python Object output. Experienced spreadsheet users often wonder whether Python in Excel is worth the extra complexity.

The Complete Excel Course with AI Integration

From formulas and pivot tables to Power Query, DAX, VBA and AI with Copilot, ChatGPT and Claude — hands-on from the first lesson.

By Sagnik Bhattacharya and Virginia Thorn, Primetime Emmy Award winner

Buy now

The sensible answer is to start with the few use cases where it clearly adds value, rather than trying to use Python for everything from day one.

Note: Availability can vary by version and channel. Treat this guide as current as of 5 August 2026 and check the Microsoft availability notes for your environment.

What should a beginner learn first in Python in Excel?

A beginner in Python in Excel should first learn ten things: Python cells, xl(), DataFrames, output modes, filtering, grouping, plotting, cleaning, error codes and where the data goes. Together they are the working knowledge that makes Python in Excel useful rather than novel, and the sections below take them in order. Learn those and you can do real analysis. Everything else is detail you can look up.

1. How do you run a Python cell in Excel?

To run Python in an Excel cell, type =PY(, write the code, and press Ctrl+Enter to commit it.

Type =PY( in a cell and Excel switches that cell into Python mode — the formula bar changes colour and the cell now expects Python, not Excel syntax. You can also use Formulas → Insert Python, or the shortcut Ctrl+Alt+Shift+P.

The part that trips up everyone on day one: Enter does not run the code. Enter inserts a newline, because Python cells are multi-line by default. You commit with Ctrl+Enter. If you press Enter and nothing happens, nothing is broken — you just added a blank line.

The other structural rule is calculation order. Python cells do not follow Excel's dependency graph. They run in row-major order — left to right along a row, then down to the next row, across the whole workbook. A Python cell in B2 can use a variable defined in A2, but a cell in A2 cannot use a variable defined in B2, even if you write a reference between them. When results come back stale or undefined, check the physical layout before you debug the code.

2. How does data get into Python in Excel?

Python in Excel reads workbook data only through the xl() function, which you hand a range, Table or name. It is Excel-flavoured, not Python-flavoured:

# A plain range — no headers, so pandas invents 0,1,2 column names
xl("A1:C50")

# The same range, treating row 1 as column names
xl("A1:C50", headers=True)

# A named Excel Table — the option worth defaulting to
xl("SalesData[#All]", headers=True)

# A single cell, which comes back as a scalar, not a DataFrame
xl("B7")

# A whole column from a Table
xl("SalesData[Revenue]")

Use Tables (Ctrl+T) rather than raw ranges wherever you can. A Table grows when rows are appended, so xl("SalesData[#All]", headers=True) keeps working after new data arrives. A hard-coded xl("A1:C50") silently ignores row 51 onwards, and nothing in the output tells you it happened.

Note the headers=True argument specifically. Leave it off and pandas treats your header row as data, which turns every numeric column into an object column, and then every numeric operation you try afterwards fails with a type error that points at the wrong line.

3. What is a DataFrame, and why does it matter?

A pandas DataFrame is a table you address by name, whereas an Excel range is a grid of cells you address by position. That change is the whole learning curve; the syntax is secondary.

df = xl("SalesData[#All]", headers=True)

df.shape        # (rows, columns) — the first thing to check
df.columns      # column names, exactly as spelled in row 1
df.dtypes       # what pandas thinks each column's type is
df.head(10)     # first ten rows
df.describe()   # count, mean, std, min, quartiles, max for numeric columns

df.describe() alone replaces a block of COUNT, AVERAGE, STDEV, MIN, QUARTILE and MAX formulas, and it updates itself when the columns change. That single method is usually the moment Python in Excel starts to feel worth it.

Check df.dtypes early and often. Most confusing Python-in-Excel behaviour comes from a column being object (text) when you assumed it was float64 (a number) — usually caused by a stray "N/A", a currency symbol, or a space in an otherwise numeric column.

4. What is the difference between Excel Value and Python Object?

Excel Value spills the result into the grid as ordinary cells, while Python Object keeps it as one object inside the cell.

Every Python cell returns its result in one of two modes, toggled from the small icon at the left of the formula bar or with Ctrl+Alt+Shift+M:

ModeWhat lands in the gridUse it when
Python Object (default)A single card showing something like DataFrame (150 rows × 4 columns)The result is an intermediate step another Python cell will consume
Excel ValueThe data spilled into real cells you can filter, chart and reference from formulasThe result is the answer, and Excel formulas need to read it

Beginners routinely think their code failed because they see one card instead of a table. The code ran fine — the cell is in Python Object mode. Switch it to Excel Value and 150 rows spill out.

The reverse matters too. Keep intermediate steps as Python Objects: spilling a 50,000-row DataFrame into the grid just so the next cell can read it back is slow and clutters the sheet. Spill only the final result.

5. How do you filter rows in Python in Excel?

Filtering in pandas means writing a condition that produces True/False for every row, then indexing with it.

df = xl("SalesData[#All]", headers=True)

# One condition
high = df[df["Revenue"] > 10000]

# Multiple conditions — round brackets are mandatory, and it is & / | not and / or
q4_uk = df[(df["Region"] == "UK") & (df["Quarter"] == "Q4")]

# Membership, instead of chained ORs
core = df[df["Region"].isin(["UK", "Germany", "France"])]

# Text matching
enterprise = df[df["Segment"].str.contains("Enterprise", na=False)]

enterprise

Two syntax rules cause nearly every beginner error here. Use & and |, never Python's and / or — the plain keywords raise "truth value of a Series is ambiguous". And wrap each condition in round brackets, because & binds tighter than > in Python, so leaving them off compares the wrong things.

Pass na=False to .str.contains() whenever the column might hold blanks, or empty cells raise instead of simply not matching.

6. When does GroupBy beat a PivotTable?

GroupBy beats a PivotTable when the summary is a repeatable step in a longer chain, or when you need several different aggregations at once. A PivotTable is still faster for a one-off summary.

df = xl("SalesData[#All]", headers=True)

# Revenue by region
df.groupby("Region")["Revenue"].sum()

# Two levels of grouping
df.groupby(["Region", "Segment"])["Revenue"].sum()

# Different aggregations per column, named cleanly
summary = df.groupby("Region").agg(
    total_revenue=("Revenue", "sum"),
    average_deal=("Revenue", "mean"),
    deal_count=("Revenue", "count"),
    best_deal=("Revenue", "max"),
)
summary.reset_index()

The .agg() form is the one to learn properly. Building that same four-metric-by-region table with formulas means SUMIFS, AVERAGEIFS, COUNTIFS and MAXIFS, each repeated per region, each needing a hard-coded region list that breaks when a new region appears. The Python version discovers the regions itself.

Call .reset_index() before returning to the grid. Without it the grouping column is a pandas index, and it disappears when the result spills into Excel — you get numbers with nothing labelling them.

If you want to learn PivotTables for the one-off summaries where they are still faster, try The Complete Excel Course with AI Integration on Coding Liquids.

7. How do you make a chart in Python in Excel?

To make a chart in Python in Excel, plot it with matplotlib in a Python cell, which returns the chart as an image object. Switch the cell to Excel Value to draw the chart inside the cell and resize the row and column to see it properly, or right-click and select Display Plot over Cells to float it over the grid.

import matplotlib.pyplot as plt

df = xl("SalesData[#All]", headers=True)
by_region = df.groupby("Region")["Revenue"].sum().sort_values()

fig, ax = plt.subplots(figsize=(8, 4.5))
by_region.plot(kind="barh", ax=ax, color="#4C78A8")
ax.set_xlabel("Revenue")
ax.set_title("Revenue by region")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig

Ending the cell with the figure object (fig) makes it clear which chart the cell returns. Python in Excel also picks up a plot when the cell ends on a plotting call such as plt.title() or plt.show(), as Microsoft's own examples do.

Be honest about when this is worth it. For a bar chart of ten regions, a native Excel chart is faster to build and easier for colleagues to edit. Reach for matplotlib when you want something native charts do badly: small multiples, distribution plots, regression overlays, or a chart whose styling you need identical across twenty workbooks.

The Complete Excel Course with AI Integration

From formulas and pivot tables to Power Query, DAX, VBA and AI with Copilot, ChatGPT and Claude — hands-on from the first lesson.

By Sagnik Bhattacharya and Virginia Thorn, Primetime Emmy Award winner

Buy now

8. How do you clean data in Python in Excel?

To clean data in Python in Excel, load the raw export with xl() and use pandas to strip whitespace, convert text to numbers and dates, standardise spellings and drop duplicate rows. Cleaning is where Python in Excel genuinely saves hours, and it is the least discussed use case.

df = xl("RawExport[#All]", headers=True)

# Strip whitespace from every text column at once
for col in df.select_dtypes("object"):
    df[col] = df[col].str.strip()

# Force a stubborn text column to numeric; unparseable values become NaN
df["Revenue"] = pd.to_numeric(df["Revenue"], errors="coerce")

# Parse dates that arrived as text, day-first as UK exports usually are
df["OrderDate"] = pd.to_datetime(df["OrderDate"], dayfirst=True, errors="coerce")

# Standardise inconsistent category spellings
df["Region"] = df["Region"].str.title().replace({"Uk": "UK", "Usa": "USA"})

# Remove exact duplicate rows, keeping the first
df = df.drop_duplicates()

# What is still missing, by column
df.isna().sum()

errors="coerce" is the important habit. It converts anything unparseable to NaN instead of throwing, so one bad row out of 40,000 does not kill the whole cell. Then df.isna().sum() tells you exactly how many failed and in which column — which is a far better bug report than an exception.

Doing this cleanup with formulas means a hidden helper sheet of TRIM, VALUE, DATEVALUE and IFERROR columns that everyone is afraid to delete. Six lines of Python replace it and state the intent plainly.

9. What do the Python in Excel error codes mean?

Python in Excel error codes tell you where a problem sits: #PYTHON! means your code raised an exception, while #BUSY!, #CONNECT! and #CALC! come from the cloud runtime and its limits. Microsoft's troubleshooting page also lists #BLOCKED!, #SPILL!, #TIMEOUT! and #UNKNOWN!.

ErrorMeaningUsual fix
#PYTHON!Your code raised an exceptionRead the full traceback in the Diagnostics pane, which opens automatically; to reopen it, right-click the cell and select Diagnostics for this cell
#BUSY!Still running in the cloudWait; it usually clears by itself. If it lasts longer than 60 seconds, reset the runtime with Formulas → Reset runtime or Ctrl+Alt+Shift+F9
#CONNECT!Cannot reach the Python runtimeCheck your internet connection, then reset the runtime (Ctrl+Alt+Shift+F9) to refresh the connection with the Microsoft Cloud
#CALC!The calculation hit a Python in Excel limitRemove references to volatile cells such as RAND, or keep each calculation to 100 MB of data or less

The single most useful habit: when you see #PYTHON!, do not re-read your code first. Read the actual traceback in the Diagnostics pane, which opens automatically for #PYTHON!. It names the failing line and the exception type, which is nearly always faster than guessing.

10. Where does Python in Excel run, and where does my data go?

Python in Excel runs in a container in the Microsoft Cloud, not on your machine: your data is sent there, the code runs, and the result comes back. Four practical consequences follow, and all four are easier to learn now than to discover later:

  • Latency is real. Every recalculation is a network round trip. A workbook with thirty Python cells is noticeably slower than one with thirty formulas, and this is the main argument against using Python where a formula would do.
  • You cannot pip install. The runtime ships a fixed Anaconda distribution — pandas, numpy, matplotlib, seaborn, statsmodels, scikit-learn and the rest of the standard stack are preloaded. If a library is not in that set, it is not available.
  • It needs a connection. Python cells do not recalculate offline. They hold their last computed value, which is fine for reading but means the workbook is not self-contained.
  • Sensitive data leaves your device. This is the one to raise before rolling it out to a team. Check your organisation's data handling rules before putting personal, financial or client data through a Python cell — the answer is often "not without approval".

There is also no documented bridge to VBA. The Python code cannot see your macros or VBA code, the PY function cannot be combined with other Excel functions, and a Python cell can only return values or images, not write to other cells the way a macro can. Python in Excel computes and returns a value; it does not automate the application.

Worked example: a churn analysis in four cells

A customer-success team has an export with one row per customer: signup date, cancellation date (blank if still active), monthly revenue and segment. The question is which segments churn worst. Four Python cells answer it end to end.

Cell B1 — load and clean:

df = xl("Customers[#All]", headers=True)
df["SignupDate"] = pd.to_datetime(df["SignupDate"], dayfirst=True, errors="coerce")
df["CancelDate"] = pd.to_datetime(df["CancelDate"], dayfirst=True, errors="coerce")
df["MonthlyRevenue"] = pd.to_numeric(df["MonthlyRevenue"], errors="coerce")
df = df.dropna(subset=["SignupDate", "MonthlyRevenue"])
df

Cell B2 — derive the churn flag and tenure:

df = xl("B1")
df["Churned"] = df["CancelDate"].notna()
end = df["CancelDate"].fillna(pd.Timestamp.today())
df["TenureMonths"] = ((end - df["SignupDate"]).dt.days / 30.44).round(1)
df

Cell B3 — churn rate and revenue at risk by segment:

df = xl("B2")
result = df.groupby("Segment").agg(
    customers=("Churned", "size"),
    churned=("Churned", "sum"),
    avg_tenure_months=("TenureMonths", "mean"),
    monthly_revenue=("MonthlyRevenue", "sum"),
)
result["churn_rate_pct"] = (result["churned"] / result["customers"] * 100).round(1)
result = result.sort_values("churn_rate_pct", ascending=False)
result.reset_index()

Set that final cell to Excel Value and the table spills into the grid, where conditional formatting and ordinary formulas work on it normally.

Cell B4 — the chart:

import matplotlib.pyplot as plt

result = xl("B3")
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.barh(result["Segment"], result["churn_rate_pct"], color="#E45756")
ax.set_xlabel("Churn rate (%)")
ax.set_title("Churn rate by segment")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig

Notice the pattern: each cell reads the previous cell's DataFrame with xl("B1"), xl("B2") and so on. Intermediate cells stay as Python Objects; only B3 spills. That is the idiomatic structure — a short chain of named steps rather than one enormous cell, so when something breaks you can see which step produced the wrong shape.

When is a formula still better than Python in Excel?

A formula is still better than Python in Excel for lookups, simple conditional maths and anything a colleague must edit without reading code.

TaskBetter toolWhy
Look up a value in another tableXLOOKUPInstant, offline, and every colleague can read it
Sum with two or three conditionsSUMIFSNo round trip, no dependency on a runtime
Summary table a manager will re-slicePivotTableInteractive; Python output is static once spilled
Four aggregations across an unknown set of groupsPython .agg()Discovers the groups; formulas need them hard-coded
Cleaning a messy recurring exportPythonSix readable lines instead of a hidden helper sheet
Regression, correlation matrix, distributionsPythonstatsmodels and scikit-learn do properly what Excel approximates
Repeating identical charts across many workbooksPythonStyling is code, so it is consistent by construction

The honest summary: Python in Excel is not a replacement for Excel. It is a better tool for cleaning, multi-metric aggregation and statistics, and a worse tool for lookups, simple conditional maths and anything a colleague needs to edit without reading code.

Common mistakes

  • Pressing Enter instead of Ctrl+Enter and concluding the feature is broken.
  • Forgetting headers=True, which turns every numeric column into text and breaks the next operation with a confusing type error.
  • Using and / or in a filter instead of & / |, producing "truth value of a Series is ambiguous".
  • Not calling .reset_index() after a groupby, so the labels vanish when the result reaches the grid.
  • Expecting a chart to appear in the cell straight away, when Python in Excel returns it as an image object until you switch the cell to Excel Value.
  • Ignoring row-major order and referencing a variable defined in a cell that runs later.
  • Assuming the code runs locally and putting client data through a cloud runtime without checking policy.
  • Rewriting working formulas in Python for its own sake, adding latency and a runtime dependency for no analytical gain.

When to use something else

If you need AI help more than code, go to Copilot in Excel with Python. If you want to understand the in-grid Python surface itself, the PY function guide is the next logical step. For reshaping and merging large exports on a schedule, Power Query is usually the better home than a Python cell.

The Complete Excel Course with AI Integration

From formulas and pivot tables to Power Query, DAX, VBA and AI with Copilot, ChatGPT and Claude — hands-on from the first lesson.

By Sagnik Bhattacharya and Virginia Thorn, Primetime Emmy Award winner

Buy now

Frequently asked questions

What should I learn first in Python in Excel?

In order: committing a cell with Ctrl+Enter, loading a Table with xl("Table[#All]", headers=True), checking df.dtypes and df.describe(), switching between Excel Value and Python Object, and one groupby().agg(). That is enough to do genuine analysis; everything else can be looked up as needed.

Why does pressing Enter not run my Python cell?

Python cells are multi-line, so Enter inserts a newline instead of running the code. Commit the cell with Ctrl+Enter. Nothing is broken if you press Enter and see nothing happen: you have only added a blank line. This is the single most common first-hour confusion for beginners.

Why does my cell show "DataFrame (150 rows × 4 columns)" instead of my data?

The cell is in Python Object mode, which is the default, so it shows one card for the whole DataFrame. Switch it to Excel Value from the icon at the left of the formula bar, or with Ctrl+Alt+Shift+M, and the rows spill into the grid. Keep intermediate steps as Python Objects.

When is Python the right tool versus a formula?

Python wins for cleaning messy exports, computing several aggregations across groups you have not hard-coded, and real statistics. Formulas win for lookups, simple conditional maths, and anything colleagues must edit without reading code. If a formula already solves it cleanly, keep the formula.

Which libraries are available, and can I install more?

No, you cannot install more. The runtime ships a fixed Anaconda distribution: pandas, numpy, matplotlib, seaborn, statsmodels and scikit-learn among others are preloaded. You cannot pip install into it, and if a package is not included it is not available, so check that what you need is in the standard stack first.

Where does the code run, and is my data sent anywhere?

The code runs in a container in the Microsoft Cloud, not on your machine, so workbook data is transmitted there and back on every recalculation. That also means Python cells do not recalculate offline. Check your organisation's data handling rules before using it on personal, financial or client data.

Why do my Python cells calculate in the wrong order?

They run in row-major order across the workbook — left to right along a row, then down — not in Excel's usual dependency order. A cell can only use variables defined in cells that come earlier in that reading order. Rearranging the cells physically fixes it.

Can I call Python in Excel from VBA or a macro?

Not directly. Microsoft documents no way to run Python in Excel from VBA, the Python code cannot see your macros, and the PY function cannot be combined with other Excel functions. A Python cell computes a value or image and returns it; it does not automate Excel. If you need to automate the application itself, that still belongs in a macro or another tool.

What does #PYTHON! mean?

#PYTHON! means your code raised an exception. Read the full traceback in the Diagnostics pane, which opens automatically and names the failing line and exception type; to reopen it, right-click the cell and select Diagnostics for this cell. That is considerably faster than re-reading the code and guessing.

How do I start a Python cell in Excel?

Type =PY( in a cell, or use Formulas, then Insert Python, to switch the cell into Python mode. Write your code, using Enter for new lines, and commit it with Ctrl+Enter. The code runs in a secure Microsoft Cloud runtime rather than on your machine, so Python cells need a connection to recalculate.

Related guides on this site

Official references