Python in Excel tutorial1
Python in Excel tutorial1
e
l
c
Get started with Python in E
Easily combine Python and Excel analytics in one workbook with Python in Excel, no s
Just type Python in a cell, and calculations run securely in the Microsoft Cloud. Result
plots and visualizations, appear in your worksheet.
Available now on Excel for Windows. Stay informed by joining the waitlist at aka.ms/e
Let's go
>
c
o
n
t
Ii
n
n
s
u
te
o
n
t
o
t
h
e
n
e
x
t
s
e
c
t
i
o
n
:
e
d
i
t
i
n
g
.
Become familiar with Python (=PY
1. To write or edit Python code, use the Python formula by typing =PY( in a cell or go to
Formulas > Python and select Insert Python.
Formulas >
Python
4. Give it a try! In cell F7, enter =PY( to enable Python and then enter "1+1". Unlike
regular Excel formulas, you need to use Ctrl+Enter to commit changes.
ormulas tab to
arted with Python
ction-31d1c523-fb13-46ab-96a4-d1a90a9e512f
I
n
s
t
C
o
l
u
Learn about Python output
1. By default, Python formulas return results as a Python Object. The second output type is an
Excel Value. Use the controls next to the formula bar or in the right-click menu to adjust the outpu
type.
Right-click menu
GOOD TO KNOW
You can also use the keyboard shortcut
Ctrl+Alt+Shift+M to toggle between
output types.
or the
formula
bar.
While
editing,
use the
keyboar
d
shortcut
Ctrl+F2
GOOD TO KNOW: The default output type is a Python Object. You can use t
to
toggle
betwee
n the
cell and
formula
bar.
thon Object. You can use the keyboard shortcut Ctrl+Alt+Shift+M to toggle between output types.
put types.
I
n
s
t
C
e
l
l
C
e
G
lo
l
t
Reference cells to bring data into
To import data, use an Excel worksheet or a Power Query data source. To protect your security,
pandas.read_csv and pandas.read_excel aren’t compatible with Python in Excel.
1. Look at DataFrames created from the example data in cells D4 to F10. H5 is a Python Objects, a
L5 is Excel Values. Multi-cell references like D4:F10 are pandas DataFrames by default.
2. In the code, you'll notice an xl() function that is used to interface between Excel and Python.
accepts
Excel objects like ranges, tables, queries and names as the first parameter and an optional param
for headers as the second.
3. You can create new references by selecting data on the grid or using the keyboard. Use F2 to
between Enter and Edit mode and arrow keys to select cells.
4. Try it out! In cells H15 and L15, create new DataFrames using Range data. In cells H28 and L
try it out with the data in the Excel table. For Excel tables, use full references like
=PY(xl("Table1[#All]")).
4 236 178
5 354 163
6 192 148
7 294 153
8 263 173
9 199 162
10 168 174
Try here!
Try here!
O KNOW
he entire table using
oard, use Ctrl+Shift
rrow > Down
O KNOW
he entire table using
oard, use Ctrl+Shift
rrow > Down
lect the entire table using your keyboard, use Ctrl+Shift > Right arrow > Down arrow.
I
n
s
t
G
o
t
Use Power Query to import extern
To import data from external sources, use Data > Get Data which uses Power Query. Every impo
new
query. For more details, visit aka.ms/pqxl.
Note: If you have existing workbooks with Power Query queries, start with step 6.
1. Let's import test data from the Northwind OData service. Copy the link to use in step 2:
https://services.odata.org/northwind/northwind.svc/
2. Go to Data > Get Data > From Other Sources > From OData Feed, paste the link and se
3. In the Navigator dialog, select the Categories table then Load To… under the Load menu. I
Data
Dialog, choose Only Create Connection and then OK.
Power Query
Navigator
4. The Queries & Connections pane will list the connection to the Categories table. You can op
anytime by going to Data > Queries & Connections.
5. Now let's create our DataFrame with external data in cell F6 by referencing the name
of the Power Query connection within the xl() function. For this example, we’d enter: =PY(xl("Ca
Cells D6 to E10 contain data with 2 columns. One for Widget, and one for Sales.
G
o
t
Understand Python calculation ord
Cells D6 to E10 contain data with 2 columns. One for Widget, and one for Sales.
1. Python cells return the last assignment or expression. If None is returned, you'll see a
NoneType Python Object. Try both statements in cell H6 to see how it works:
1+1
print("Hello world!")
2. Python in Excel cells calculate in row-major order, left-to-right across rows, then down the
worksheet. For example, in cell H10 there's a DataFrame named df with Widget sales data.
Running "df['Sales'].sum()" in H8 results in a #PYTHON! error because df isn't defined yet.
However, it works in H12 because H8 precedes H12 in the calculation order.
3. This calculation order also applies across worksheets, based on their left-to-right order. Global
variables can be used across worksheets, calculating based on the worksheet order.
4. You can view error messages in a dialog by selecting the icon that appears selecting the cell
with
an error, then choosing "Show Error Message".
GOOD TO KNOW
For languages that read right-to-left,
Python cells and worksheets calculate
across a row from right-to-left.
hon Object returned since that is the last expression.
C
e
l
l
G
o
t
Understand a few errors
1. #BUSY!: Displays when a Python formula is calculating.
2. #PYTHON!: Indicates an issue with the Python code. By default, the Python Editor
pane automatically opens with more details on the error. To see how this works, in cell
D6 enable Python and enter "1/0". You'll see a #PYTHON! error returned and the pane opened.
3. #CONNECT!: Indicates issues with the Python cloud service. If you see this error, reset
your Python global variables in your workbook via Formulas > Python > Reset, or reset
the Python runtime via Formulas > Python > Reset > Reset Runtime. Both will trigger
recalculation unless you are in Manual recalculation mode.
4. You can also view error messages in a dialog by selecting the icon that appears
selecting the cell with an error, then choosing "Show Error Message".
Error menu
earn more about open-source libraries to use with Python in Excel, visit https://support.microsoft.com/office/ope
references are converted to DataFrames.
microsoft.com/office/open-source-libraries-and-python-in-excel-c817c897-41db-40a1-b9f3-d5ffe6d1bf3e
-d5ffe6d1bf3e
I
n
s
t
G
o
t
Create Python plots
1. You can use Python libraries to create data visualizations and plots. Try modifying the plot
type in cell H8 by choosing from the dropdown options in cell H7. As you switch the plot type,
the code recalculates and the floating image updates automatically.
2. By default, you see a Python Object with an Image data type is returned to the
cell. To view the
plot, create a linked reference of the image that can be resized. In the Insert Data or right-click
menu, select Display Plot over Cells. Alternatively, use the keyboard shortcut Ctrl+Alt+Shift+
when selecting a cell. This has been done already for Plot 1 in cell H6, but give it a try when
you
create the multiplot and histogram in the next step.
3. Try it out! Use the Python code below to create different plots. To view the plots, don't
forget to display the plot over cells as explained in step 2.
Try a Multiplot in cell H24:
decompose = seasonal_decompose(dfplots['Passengers'],model='additive', period=36)
decompose.plot()
Try a Histogram in cell H41:
plt.figure(figsize=(10,6))
plt.hist(dfplots['Passengers'], bins=20)
plt.xlabel('Passengers (in thousands)')
plt.ylabel('Frequency')
plt.title('Histogram of Passengers')
plt.show()
7/1/1949 148
8/1/1949 148
9/1/1949 136
10/1/1949 119
11/1/1949 104
12/1/1949 118
1/1/1950 115
2/1/1950 126
3/1/1950 141
4/1/1950 135
5/1/1950 125
6/1/1950 149
7/1/1950 170 Multiplot
8/1/1950 170
9/1/1950 158
10/1/1950 133
11/1/1950 114
12/1/1950 140
1/1/1951 145
2/1/1951 150
3/1/1951 178
4/1/1951 163
5/1/1951 172
6/1/1951 178
7/1/1951 199
8/1/1951 199
9/1/1951 184
10/1/1951 162
11/1/1951 146
12/1/1951 166 Histogram
1/1/1952 171
2/1/1952 180
3/1/1952 193
4/1/1952 181
5/1/1952 183
6/1/1952 218
7/1/1952 230
8/1/1952 242
9/1/1952 209
10/1/1952 191
11/1/1952 172
12/1/1952 194
1/1/1953 196
2/1/1953 196
3/1/1953 236
4/1/1953 235
5/1/1953 229
6/1/1953 243
7/1/1953 264
8/1/1953 272
9/1/1953 237
10/1/1953 211
11/1/1953 180
12/1/1953 201
1/1/1954 204
2/1/1954 188
3/1/1954 235
4/1/1954 227
5/1/1954 234
6/1/1954 264
7/1/1954 302
8/1/1954 293
9/1/1954 259
10/1/1954 229
11/1/1954 203
12/1/1954 229
1/1/1955 242
2/1/1955 233
3/1/1955 267
4/1/1955 269
5/1/1955 270
6/1/1955 315
7/1/1955 364
8/1/1955 347
9/1/1955 312
10/1/1955 274
11/1/1955 237
12/1/1955 278
1/1/1956 284
2/1/1956 277
3/1/1956 317
4/1/1956 313
5/1/1956 318
6/1/1956 374
7/1/1956 413
8/1/1956 405
9/1/1956 355
10/1/1956 306
11/1/1956 271
12/1/1956 306
1/1/1957 315
2/1/1957 301
3/1/1957 356
4/1/1957 348
5/1/1957 355
6/1/1957 422
7/1/1957 465
8/1/1957 467
9/1/1957 404
10/1/1957 347
11/1/1957 305
12/1/1957 336
1/1/1958 340
2/1/1958 318
3/1/1958 362
4/1/1958 348
5/1/1958 363
6/1/1958 435
7/1/1958 491
8/1/1958 505
9/1/1958 404
10/1/1958 359
11/1/1958 310
12/1/1958 337
1/1/1959 360
2/1/1959 342
3/1/1959 406
4/1/1959 396
5/1/1959 420
6/1/1959 472
7/1/1959 548
8/1/1959 559
9/1/1959 463
10/1/1959 407
11/1/1959 362
12/1/1959 405
1/1/1960 417
2/1/1960 391
3/1/1960 419
4/1/1960 461
5/1/1960 472
6/1/1960 535
7/1/1960 622
8/1/1960 606
9/1/1960 508
10/1/1960 461
11/1/1960 390
12/1/1960 432
#NAME?
#NAME?
line
#NAME?
Try here!
Try here!
I
n
s
t
Use the Python editor to write or v
code
The Python editor allows you to write and edit Python formulas using a dedicated code editor with
similar capabilities as those available in Python notebook environments. It is designed to complem
the Python in Excel experience with an editing surface optimized for more complex and longer Py
code snippets.
2. Along with writing and editing Python code, the Python Editor is where your standard error (
and standard output (stdout) like print statements will be returned. If you don't want the pane t
automatically in these cases, click on the menu on the top right then uncheck "Show automatic
workbook".
3. Give it a try! You can edit any existing formulas or create new Python formulas in the editor.
GO
Yo
Ct
B
3
.
Ctrl+Shift+U
F2
F9
B
3
.
Learn more
In addition to this template, there are many resources available to continue learning about
Python in Excel.
Python Center tips and samples. Open the Python Center by going to
#VALUE! Formulas > Python > Insert Python.
Lastly, Python in Excel is built for sharing. You can share workbooks with others and they can
interact with and refresh Python formulas without needing to worry about any set up.
Try it out by sharing this template with others who may be interested in Python in Exc
arning about
d in Python in Excel!