Python in Excel workbook with DataFrame, groupby, and pandas plot examples

Get the Python in Excel Practice Workbook

Follow along with the exact file from this tutorial. Build a DataFrame, run describe() and groupby(), plot a chart with pandas, and extract URLs with Regex, all inside Excel.

What is Python in Excel?

Microsoft has added Python to Excel. Now, you can run Python scripts directly in your spreadsheets.

This powerful combination lets you use Pythonโ€™s advanced tools without leaving Excel.

What is Python?

Python is a popular programming language known for its simplicity and versatility. Itโ€™s used for data analysis, automation, and more.

With Python in Excel, you get the best of both worlds.

Benefits of Using Python in Excel:

  • Efficiency: Automate repetitive tasks and save time.
  • Advanced Analysis: Perform complex data calculations with ease with Python libraries like Pandas and NumPy.
  • Better Visuals: Create detailed and dynamic charts and graphs with tools like Matplotlib and Seaborn.
  • Integration: Seamlessly blend Python’s capabilities with Excel’s familiar interface.

How Do You Turn On Python in Excel?

To use Python in Excel, you can use 2 options:

  • Go to the Formulas tab and click “Insert Python” in the Python section.
Excel Formulas ribbon showing the Insert Python button in the Python section
Click Insert Python on the Formulas tab to open a Python cell.
  • Or, type in “=PY” in a cell and press Tab.
Syntax tooltip for =PY in Excel showing the Creates Python formulas autocomplete
Type =PY in a cell and press Tab to enter Python mode.

How Do You Create a DataFrame in Excel?

To use Excel with Python, you need to create a DataFrame. This makes data manipulation easy and efficient.

๐Ÿ’ก Python for Excel works in the cloud, so youโ€™ll need an internet connection to access it.

What is a DataFrame?

A DataFrame is like a table in Excel or a database. It has rows and columns for storing data.

You can use DataFrames to handle large datasets easily. It can hold the content of an entire Excel data table in a single cell.

DataFrames are part of the Pandas library in Python. Pandas provides strong tools for data analysis, making it simple to work with your data.

๐Ÿ’ก In Python for Excel, a DataFrame is the default object used for two-dimensional ranges.

How to Create a DataFrame in Excel

Here are the steps to create a Python DataFrame in Excel:

  • Type “=PY” in a cell and press Tab.
  • Select the data in your table (in our example A2:D98).
Excel range A2:D98 selected for xl formula to build a Python DataFrame
Select your data range, here A2:D98, to reference it inside the Python formula.
  • Press Ctrl + Enter to create the Python DataFrame
Excel cell showing collapsed DataFrame object after running Python formula
Press Ctrl + Enter to commit the code. The cell now shows a collapsed DataFrame object.

Output Types for DataFrames

Python in Excel can output a DataFrame in two ways: as a Python object or converted to Excel values.

Python Objects

Useful for reusing results in future Python calculations.

When a DataFrame is returned as a Python object in Excel, the cell shows โ€œDataFrameโ€ with a “PY” in square brackets before it.

Excel cell F2 showing collapsed Python DataFrame object with PY icon
A Python object shows as [PY]DataFrame in the cell until you expand it.
  • To see the details within a DataFrame in Excel, click the [PY] icon in the cell to show the card.
Expanded 96x4 Python DataFrame card showing Date, Product, and Quantity columns
Click the [PY] icon to expand the card and preview the full DataFrame, powered by Anaconda.
  • Alternatively, press the keyboard shortcut Ctrl + Shift + F5.

Excel Values

You can also output DataFrames translated to the closest Excel format. This allows you to use Excel features like charts, formulas, and conditional formatting.

Excel columns F-I showing Python DataFrame converted to native Excel values
Choosing Excel Value converts the DataFrame into native cells you can chart or format.

๐Ÿ’ก If a cell in the output range (e.g., F2 to I98) already contains a value, the Python cell will return a #SPILL! error instead of the Python output.

Excel #SPILL error when Python DataFrame output range is already occupied
A value sitting inside the output range, here “Learn Excel with XelPlus” in G6, blocks the spill and triggers a #SPILL! error.

๐Ÿ’ก To learn more about #SPILL! errors and how to correct them, see this detailed article.

Controlling Python Output Types in Excel

You can control how Python outputs DataFrames in Excel using the Python output menu in the formula bar.

  1. Click on the cell with the DataFrame.
  2. In the formula bar, look to the left of the green PY icon for the dropdown menu.
  3. Choose the output type: either Python Object or Excel Value.
Excel Python Output dropdown menu with Python Object and Excel Value options
Click the dropdown left of the PY icon to switch between Python Object and Excel Value output.
  • Alternatively, you can right-click on the cell containing the DataFrame. Then choose “Python Output,” and select the desired output format.

Choosing ‘Python Object’ keeps the data in Python format. ‘Excel Value’ converts it to an Excel-friendly format.

Popular Course

Python in Excel For the Real World

A hands-on course for Excel users: use Python to forecast, apply machine learning, and build charts Excel can’t make. No coding background needed.
Learn More

How to Use DataFrames in Excel

Describe Data with Pandas

Use the describe() Function in Pandas to get basic statistical insights about your data in the DataFrame.

This function provides details such as count, mean, standard deviation, minimum, maximum, and percentiles.

Steps to Use describe() in Excel:

  • Select a Cell: Click on a cell in Excel where you want to display the output, e.g., F4.
  • Enter Python Mode: Type =PY in the formula bar and press Tab to enter Python mode.
  • Reference the DataFrame: Click on the cell that contains your DataFrame, e.g., F2.
  • Use the Describe Function: Add .describe() to the reference and press Ctrl + Enter to run the code.
=PY(F2.describe())
Excel cell F4 showing collapsed DataFrame result from the describe function
Press Ctrl + Enter to run .describe(). The result collapses into a DataFrame object in F4.
  • Change Output Type: Make sure the Python output is set to Excel Data.
Excel describe function output showing count, mean, min, and percentile stats
Expand the DataFrame to see count, mean, min, max, and percentile breakdowns for each column.

Using the describe() function helps you quickly understand the distribution and central tendency of your data, making it easier to identify trends and outliers.

Name Your DataFrame

I recommend giving your DataFrame a name for easier referencing and better code readability.

When you name your DataFrame, you can quickly and clearly refer to it in your code. Here’s how to do it:

  • Select the Cell: Click on the cell with the DataFrame.
  • Assign a Name: Update the beginning of the formula by giving it a name, e.g., df.
Excel formula bar showing df = xl syntax to name a Python DataFrame
Add a name like df before the xl() reference, then press Ctrl + Enter to apply it.
  • Execute: Press Ctrl + Enter to apply the name

Naming the DataFrame allows you to use a simple reference throughout your code. This is much easier than using the full data frame code each time you need to access it.

How Do You Calculate Sum, Average, and Groupby with Python in Excel?

Simple Sum and Average Calculations

The Pandas library offers many functionalities for data manipulation and analysis. Some simple ones include calculating the sum and average of a column. Hereโ€™s how you can perform these calculations in Excel using Python:

  • Select a Cell: Click on a cell in Excel where you want to display the result, e.g., K4.
  • Enter Python Mode: Use the keyboard shortcut Ctrl + Alt + Shift + P to enter Python mode.
  • Reference the DataFrame: Use the name of your DataFrame, e.g., df, and the header of the column you want to calculate, e.g., Sales.
  • Add the SUM() Function: Type the formula to calculate the sum.
 =PY(df.Sales.sum())
Syntax Tooltip: Excel formula df.Sales.sum() with Ctrl+Enter commit hint
Reference df.Sales.sum() to total the Sales column, then press Ctrl + Enter to run it.
  • Execute: Press Ctrl + Enter to run the calculation

This will calculate the total of the Sales column in cell K4.

Similarly, to calculate the average of the Sales column:

 =PY(df.Sales.mean())
Syntax Tooltip: Excel formula df.Sales.mean() with Ctrl+Enter commit hint
Swap .sum() for .mean() to calculate the average of the Sales column instead.

Aggregating Data with Pandas Series in Excel

Apart from simple operations like sum and average, you can also easily aggregate your data using Pandas Series.

A Series is similar to a single column in a table. It’s a one-dimensional array that can hold data of any type.

For example, you can use the groupby() function to aggregate your DataFrame by date:

  • Enter the Python code: We’ll reference the dataframe “df” and apply the groupby() function to aggregate the sales column by date
=PY(df.groupby("Date").Sales.sum())
Syntax Tooltip: Excel groupby Date Sales sum formula with Ctrl+Enter hint
Reference df.groupby(“Date”).Sales.sum() to total Sales by date, then press Ctrl + Enter.
  • Change Output Type: In the formula bar, use the dropdown menu next to the green PY icon to change the output from Python Series to Excel data.
Excel table showing Sales grouped by Date after switching output to Excel data
Switch the output to Excel data to see Sales totals broken out by date in a real table.

You can also change the aggregation easily by using Grouper. A Grouper is a Pandas class that allows you to group data by a specific frequency.

How to Use Grouper:

=PY(df.groupby(pd.Grouper(key="Date", freq="M")).Sales.sum())
  • key: Represents the column you want to group by, in this case, “Date”.
  • freq: Stands for frequency. “M” means monthly, so the data will be aggregated on a monthly basis.

After executing the code with Ctrl + Enter, Excel will display the aggregated sales data on a monthly basis.

Excel table showing Sales totals grouped by month using Pandas Grouper
Grouper with freq=”M” rolls up Sales into monthly totals instead of daily ones.

Using the Grouper function in Pandas allows you to perform flexible and powerful data aggregations based on different time frequencies. This feature is especially useful for time series data and helps you uncover trends and patterns over specific periods.

Prefer to skip the code? You can group dates the same way using a PivotTable instead of Python, useful if you’re working with a teammate who doesn’t use Python.

How Do You Plot a Chart with Python in Excel?

You can use the Pandas plot() method to create charts directly in Excel cells. Here’s how to do it:

  • Group Data: Aggregate your data by date on a monthly basis.
forchart = df.groupby(pd.Grouper(key="Date", freq="M")).Sales.sum()
  • Create the Plot: Use the plot() method to create a line chart.
forchart.plot(x="Date", y="Sales", kind="line")
Excel Python code defining forchart variable and calling plot with kind line
Both lines run together: the first groups Sales by month, the second plots it as a line chart.
  • Parameters:
    • forchart: The variable name assigned to the grouped data for the chart.
    • x: Defines which data to show on the x-axis, e.g., the date.
    • y: Defines which data to show on the y-axis, e.g., sales values.
    • kind: Defines the type of chart to plot, e.g., line, area, bar.
  • Increase the size of the chart: Merge some cells next to the cell with the chart.
Line chart of monthly Sales in Excel created with pandas plot function
forchart.plot() renders a line chart directly in the cell. Sales peak in August, then drop through October.

Why Does Cell Order Matter in Python in Excel?

In Excel, Python calculations follow a specific order:

  • Top to Bottom: Just like traditional Python code, Python statements in Excel cells calculate from top to bottom within a single cell.
  • Across Rows and Down Columns: In an Excel worksheet, Python cells calculate from left to right across each row. After finishing one row, it moves to the next row.

Understanding this calculation order helps you organize your data and formulas efficiently, preventing errors and ensuring your results are accurate.

Example Setup 1:

  • DataFrame Location: The DataFrame holding the data is in cell F2.
  • Average Calculation: We want to calculate the average in cell K4.

Since Python in Excel calculates from left to right, the setup works. Cell F2 (where the DataFrame is defined) is to the left of cell K4 (where we calculate the average).

Excel showing valid Python calculation order with DataFrame left of average cell
F2 (DataFrame) sits left of K4 (average), so the calculation runs without error.

Let’s see what happens if we move the calculation

Example Setup 2:

  • DataFrame Location: The DataFrame holding the data is in cell F2.
  • Average Calculation: We want to calculate the average in cell B1.

This causes an error because it tries to reference Sales from the DataFrame before itโ€™s defined.

Excel PYTHON error and AttributeError when DataFrame is referenced before defined
B1 tries to reference Sales before F2 defines the DataFrame, triggering an AttributeError.

Key Points to Remember

  • Order Matters: Always place your variable definitions in cells that come before the cells where you use them.
  • Across Worksheets: Organize your worksheets so that data and variable definitions come first, followed by your analysis and calculations.

How Do You Extract URLs from Text with Python in Excel?

You can find and extract URLs from text data in your Excel sheets using Python and regular expressions (Regex).

Excel Feedback column with highlighted URLs mapped to a separate URLs column
The goal: pull every URL out of the Feedback column into its own column.

Here is the Step-by-Step Guide:

Step 1: Import the ‘re’ Library:

The re library allows you to work with regular expressions in Python, which are powerful tools for pattern matching. Since it’s not part of the default libraries, we need to import it. We will do this in cell A1.

=import re
"re loaded"
Excel cell A1 running import re with re loaded confirmation message
Run import re in cell A1 first. The “re loaded” message confirms the library is ready.

Step 2: Define the DataFrame

In this step, we’re sending the Excel data we want to use to Python. Suppose the data is in an Excel table named “Table1” located in cells A3 to A7. We’ll include the headers using the ‘#All’ argument and define the DataFrame in cell B1:

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

๐Ÿ’ก By referencing the table, we ensure that all data is included, even if new rows are added later.

Excel formula referencing Table1 with #All to define a Python DataFrame
Reference Table1[#All] with headers=True so new rows added later stay included automatically.

Step 3: Apply the Extraction Code

We use Regular Expression (Regex) pattern to extract the URLs.

pattern_combined = r'https://\S+|http://\S+|www.\S+|\b[^ ]+.com\b'
Function to run on each text
def extract_urls(text):
url_pattern = re.compile(pattern_combined)
urls = url_pattern.findall(text)
return ', '.join(urls)
Apply the function to the dataframe
df['URLs'] = df['Feedback'].apply(extract_urls)
Filter out rows without URLs and keep only the URLs column
df_urls_only = df[df['URLs'] != ''][['URLs']]
Python regex code extracting URLs from Feedback column into new column
The complete function: compile the regex pattern, apply it to Feedback, then filter to rows with a match.
  • The Regex pattern r’https://\S+|http://\S+|www.\S+|\b[^ ]+.com\b’ is used to find URLs in different formats.
  • Use the apply() method to apply the function to the ‘Feedback’ column of the DataFrame.
  • Filter out rows without URL and store the extracted URLs in a new column ‘URLs’.

After executing the code with Ctrl + Enter, we get the extracted URLs displayed in the specified cells.

Excel Feedback column with extracted URLs shown in adjacent URLs column
After Ctrl + Enter, the URLs column shows every link pulled from Feedback, including bare domains like google.com.

For more information about Regular Expressions, check out this detailed article.

Pandas Library

For more detailed guides and examples, check out the Pandas library.


Want more real-world Python in Excel examples? See our guide on 3 Python in Excel tricks, including cleaning messy dates and building Seaborn charts.

Who Can Use Python in Excel in 2026?

Python in Excel is available on Microsoft 365 Business and Enterprise plans with the Python in Excel license.

Standard compute is included at no extra cost and covers everyday cleanup, calculations, and charts. Heavy or fast workloads can use premium compute, a paid add-on.

Availability continues to expand across plan tiers, so confirm your specific license includes it under File > Account.

How Does Copilot Write Python in Excel for You?

As of April 2026, Edit with Copilot in Excel can write and run Python for you.

Ask Copilot to analyze your data in plain language, for example “forecast sales for next quarter,” and it generates the Python code, runs it in the secure cloud sandbox, and inserts the result, including charts, directly into your sheet.

You can also invoke Python manually inside a Copilot prompt if you want more control over the analysis. Copilot’s Plan mode, rolled out in May 2026, shows you what it intends to change before it touches your workbook.

Frequently Asked Questions

How do I turn on Python in Excel?

Go to the Formulas tab and click Insert Python, or type =PY in a cell and press Tab.

What is a DataFrame in Python in Excel?

A DataFrame is a table-like object with rows and columns, similar to an Excel range or a database table, used to store and manipulate two-dimensional data.

Why does my Python in Excel formula return an error?

Python cells calculate left to right, then top to bottom. If a formula references a DataFrame before the cell that defines it, Excel throws an AttributeError. Place your DataFrame definition in a cell before any cell that uses it.

What’s the difference between Python Object and Excel Value output?

Python Object keeps the result in Python format for reuse in further Python calculations. Excel Value converts the result into native Excel data so you can use it with formulas, charts, and conditional formatting.

Why does describe() show #NUM! for a date column?

Standard deviation can’t be calculated on datetime values, so pandas returns an error for that cell. This is expected behavior, not a bug. Focus on count, min, and max for date columns instead.

What Microsoft 365 plan do I need for Python in Excel?

Microsoft 365 Business and Enterprise plans with the Python in Excel license. Standard compute is included; premium compute is a paid add-on for heavy workloads.

Can Copilot write Python code for me in Excel?

Yes. Edit with Copilot can generate and run Python code from a plain-language prompt, or invoke Python automatically when it determines that’s the best approach.

Download the Workbook

Download the practice workbook and run every DataFrame, groupby, and chart example yourself.

Leila Gharani

Founder of XelPlus and ten-time Microsoft MVP. Leila helps over 500,000 professionals master Excel, Power BI, and data automation through practical, real-world training.