Python in Excel Tutorial1
Python in Excel Tutorial1
e
l
c
Get started with Pyth
Easily combine Python and Excel analytics in one workbook with
Just type Python in a cell, and calculations run securely in the M
plots and visualizations, appear in your worksheet.
G
o
t
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
2. Python runs securely in the Microsoft Cloud, no installation needed. CHEC
To learn
3. Changes in the cell and formula bar indicate Python is enabled. You can edit the Support
formula in
either the cell or the formula bar.
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
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
output type.
Right-click menu
GOOD TO KNOW
You can also use the keyboard shortcut
Ctrl+Alt+Shift+M to toggle between
output types.
GOOD TO KNOW: The default output type is a Python Object. You can use th
CHECK
THIS
OUT:
You can
ython Object. You can use the keyboard shortcut Ctrl+Alt+Shift+M to toggle between output types.
utput 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,
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 para
3. You can create new references by selecting data on the grid or using the keyboard. Use F2 t
toggle
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
try it out with the data in the Excel table. For Excel tables, use full references like
=PY(xl("Table1[#All]")).
Try here!
1 233 150
2 250 187
3 204 172
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 imp
a 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 s
3. In the Navigator dialog, select the Categories table then Load To… under the Load menu.
Import 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 o
pane
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("C
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".
Boo 8 DataFrame
GOOD TO KNOW
For languages that read right-to-left,
Python cells and worksheets calculate
across a row from right-to-left.
ect 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
he pane opened.
GO
OD
GOOD TO KNOW TO
With the Python in Excel add-on, you can KNO
change your calculation mode through
Formulas > Calculation > Calculation
Options.
learn more about open-source libraries to use with Python in Excel, visit https://support.microsoft.com/office/ope
ll references are converted to DataFrames.
microsoft.com/office/open-source-libraries-and-python-in-excel-c817c897-41db-40a1-b9f3-d5ffe6d1bf3e
f3-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()
01/07/49 148
01/08/49 148
01/09/49 136
01/10/49 119
01/11/49 104
01/12/49 118
01/01/50 115
01/02/50 126
01/03/50 141
01/04/50 135
01/05/50 125
01/06/50 149
01/07/50 170 Multiplot
01/08/50 170
01/09/50 158
01/10/50 133
01/11/50 114
01/12/50 140
01/01/51 145
01/02/51 150
01/03/51 178
01/04/51 163
01/05/51 172
01/06/51 178
01/07/51 199
01/08/51 199
01/09/51 184
01/10/51 162
01/11/51 146
01/12/51 166 Histogram
01/01/52 171
01/02/52 180
01/03/52 193
01/04/52 181
01/05/52 183
01/06/52 218
01/07/52 230
01/08/52 242
01/09/52 209
01/10/52 191
01/11/52 172
01/12/52 194
01/01/53 196
01/02/53 196
01/03/53 236
01/04/53 235
01/05/53 229
01/06/53 243
01/07/53 264
01/08/53 272
01/09/53 237
01/10/53 211
01/11/53 180
01/12/53 201
01/01/54 204
01/02/54 188
01/03/54 235
01/04/54 227
01/05/54 234
01/06/54 264
01/07/54 302
01/08/54 293
01/09/54 259
01/10/54 229
01/11/54 203
01/12/54 229
01/01/55 242
01/02/55 233
01/03/55 267
01/04/55 269
01/05/55 270
01/06/55 315
01/07/55 364
01/08/55 347
01/09/55 312
01/10/55 274
01/11/55 237
01/12/55 278
01/01/56 284
01/02/56 277
01/03/56 317
01/04/56 313
01/05/56 318
01/06/56 374
01/07/56 413
01/08/56 405
01/09/56 355
01/10/56 306
01/11/56 271
01/12/56 306
01/01/57 315
01/02/57 301
01/03/57 356
01/04/57 348
01/05/57 355
01/06/57 422
01/07/57 465
01/08/57 467
01/09/57 404
01/10/57 347
01/11/57 305
01/12/57 336
01/01/58 340
01/02/58 318
01/03/58 362
01/04/58 348
01/05/58 363
01/06/58 435
01/07/58 491
01/08/58 505
01/09/58 404
01/10/58 359
01/11/58 310
01/12/58 337
01/01/59 360
01/02/59 342
01/03/59 406
01/04/59 396
01/05/59 420
01/06/59 472
01/07/59 548
01/08/59 559
01/09/59 463
01/10/59 407
01/11/59 362
01/12/59 405
01/01/60 417
01/02/60 391
01/03/60 419
01/04/60 461
01/05/60 472
01/06/60 535
01/07/60 622
01/08/60 606
01/09/60 508
01/10/60 461
01/11/60 390
01/12/60 432
Libraries Loaded!
line
Try here!
Try here!
I
n
s
t
Use the Python editor to write or
code
The Python editor allows you to write and edit Python formulas using a dedicated code editor wit
similar capabilities as those available in Python notebook environments. It is designed to compl
the Python in Excel experience with an editing surface optimized for more complex and longer P
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
automatically in these cases, click on the menu on the top right then uncheck "Show automati
workbook".
3. Give it a try! You can edit any existing formulas or create new Python formulas in the editor.
GO
You
Ctr
Ctrl+Alt+Shift+M
Ctrl+Alt+Shift+P
Ctrl+Enter
Ctrl+F2
Ctrl+Shift+F5
Ctrl+Shift+U
F2
F9
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 Ex
learning about