Learn how to use Python in Microsoft Excel to analyze data, perform calculations, create charts, and automate data analysis using Python code.
Python in Excel allows you to write and execute Python code directly inside Microsoft Excel worksheets. You can use Python for data analysis, statistics, data visualization, and advanced calculations without leaving Excel.
It combines Excel’s spreadsheet capabilities with Python libraries such as pandas, NumPy, Matplotlib, and Seaborn.
|  |
You can also type:
=PY(
Enter this in a Python cell:
print("Hello, Python in Excel!")
Another example:
import mathmath.sqrt(144)
Expected result: 12
Suppose you have student marks in Excel:
| Student | Marks |
|---|---|
| Ali | 85 |
| Ahmed | 72 |
| Sara | 92 |
| Ayesha | 78 |
| Usman | 65 |
You can use Python to calculate the average:
import pandas as pd
marks = xl("A2:B6", headers=True)
marks["Marks"].mean()
Calculate the highest marks:
marks["Marks"].max()
Calculate the lowest marks:
marks["Marks"].min()
For example, create a bar chart of student marks:
import matplotlib.pyplot as plt
plt.bar(marks["Student"], marks["Marks"])
plt.title("Student Performance")
plt.xlabel("Students")
plt.ylabel("Marks")plt.show()
Excel displays the resulting chart as a Python visual.
Microsoft Excel to let you run Python scripts as formulas
| Application | Python libraries |
|---|---|
| Data cleaning | pandas, NumPy |
| Statistical analysis | SciPy, statistics |
| Data visualization | Matplotlib, Seaborn |
| Machine learning | scikit-learn |
| Data exploration | pandas |
| Predictive analysis | scikit-learn, NumPy |
| Python in Excel | Traditional Python |
|---|---|
| Runs inside Excel | Runs outside Excel |
Uses =PY() |
Uses .py files |
| Runs in Microsoft Cloud | Runs locally or on a server |
Uses xl() to access Excel data |
Uses pandas and other libraries to read files |
| Requires internet | Can work offline |
Python in Excel has security restrictions. For example, you cannot directly use pandas.read_excel() to open arbitrary local files. Import external data through Power Query instead.
Microsoft Support+1
Python in Excel requires an eligible Microsoft 365 subscription and supported Excel version. Availability differs between Business, Education, Personal and Family subscriptions.
I recommend adding a separate module:
Python in Excel: Learn Python for Data Analysis
xl()