Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Python in Excel Tutorial1

The document provides a guide on how to use Python within Excel, detailing steps to combine Python and Excel analytics, run Python code securely in the cloud, and create visualizations. It explains how to input Python formulas, manage output types, reference cells, and import external data using Power Query. Additionally, it covers error handling, calculation order, and the use of Python libraries for data analysis and plotting within Excel.

Uploaded by

Forbet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python in Excel Tutorial1

The document provides a guide on how to use Python within Excel, detailing steps to combine Python and Excel analytics, run Python code securely in the cloud, and create visualizations. It explains how to input Python formulas, manage output types, reference cells, and import external data using Power Query. Additionally, it covers error handling, calculation order, and the use of Python libraries for data analysis and plotting within Excel.

Uploaded by

Forbet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODS, PDF, TXT or read online on Scribd
You are on page 1/ 55

W

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.

Available now on Excel for Windows. Stay informed by joining th


cel
I
n
s
t

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.

CHECK THIS OUT


Select the Insert Python button in the Formulas tab to
view tips and samples to help you get started with
Python in Excel.

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.

Python in Excel cell


badge

Formula bar Python in Excel badge

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.

Next, learn more about Python output. Next Step


n (=PY)
CHECK THIS OUT:
Select Insert Python button
Formula Expected result
Try here! The value 2 as a Python Object.

ormulas tab to
arted with

CHECK THIS OUT


To learn more about =PY, visit PY function - Microsoft
Support. CHECK THIS OUT: To learn
CK THIS OUT:
ect Insert Python button in the Formulas tab to view Tips and Samples to help you get started with Python in Ex

CK THIS OUT: To learn more about =PY, visit https://support.microsoft.com/office/py-function-31d1c523-fb13-46


tarted with Python in Excel.

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

Next to formula bar


Column E is to input the Python formula. Column G is the expected result.
2. Try it out! In cell E6, enter =PY( then "1+1". Select the [PY] icon within the cell to learn more
about
Python Objects.
Column D is to input the Python formula. Column F is the expected result.
3. Do the same in cell E8. This time, change the output to an Excel Value.

Next, learn about cell references. Next Step


Formula Expected result
Try here! The value 2 as a Python Object.

Try here! The value 2 as an Excel Value.

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

for headers as the second.

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]")).

Next, learn about external data. Next Step


o Python
Example data Example: as Python Objects
Category Product Sales
Accessories Helmets $8,300
Accessories Tires and Tubes $8,700
Bikes Road Bikes $3,500

Bikes Mountain Bikes $3,100


Components Pedals $800
Components Wheels $10,000

Try it out! Range Set to Python Objects


User ID Income Spend

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 it out! Excel table Set to Python Objects


User ID Income Spend
1 233 150 Try here!
2 250 187
3 204 172
4 236 178
5 354 163
6 192 148
7 294 153
8 263 173
GOOD TO KNOW
9 199 162
10 168 174 To select the entire table using
your keyboard, use Ctrl+Shift
> Right arrow > Down
arrow.
GOOD TO KNOW
To select the entire table using
your keyboard, use Ctrl+Shift
> Right arrow > Down
arrow.
GOOD TO KNOW: To select the entire table using
Python Objects Example: as Excel Values

Category Product Sales


Accessories Helmets 8300
Accessories Tires and Tubes8700

Bikes Road Bikes 3500


Bikes Mountain Bikes3100
Components Pedals 800

Components Wheels ###

n Objects Set to Excel Values

Try here!

n Objects Set to Excel Values

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.

Import Data dialog

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

Next, learn about calculation order. Next Step


al data
Formula Expected result
Try here! DataFrame
gories").
I
n
s
t

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".

Next, learn about Python errors. Next Step


order
Example data Example Expected value
Widget Sales Try here! NoneType Python Object returned since th
Foo 5
Bar 6 Try here! #PYTHON! error because DataFrame is de
Baz 7

Boo 8 DataFrame

Try here! Correct sum (26) because DataFrame is re

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.

use DataFrame is defined below in H10.

use DataFrame is referenced in cell H10 above.


I
n
s
t

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

Next, learn more about libraries. Next Step


Formula Expected result
Try here! #PYTHON!

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.

Automatic automatically recalculates all


dependent formulas every time you make a
change in Excel. This is the default setting.

Manual recalculates formulas when you


manually trigger the process to do so.

Partial is a hybrid between manual and


automatic. This mode recalculates all
formulas automatically except those that are
typically time consuming, like Python and
Data Tables.
I
n
s
t

Use Python libraries


1. Python in Excel uses a secure, open-source library distribution from Anaconda.
The following
recommended libraries are: pandas, NumPy, scipy, scikit-learn, statsmodels, matplotlib,
seaborn, json, and regex. Note: NumPy and pandas are pre-initialized by default
using import numpy as np and import pandas as pd.
Go to cell I9 to learn about how single and multi-cell references are converted by default.
2. Settings and configuration details, like importing open-source Python libraries,
are managed through the Initialization pane. View the default configuration by selecting
Formulas > Python > Initialization.

3. The initialization pane is read-only, so you must import new libraries


in a cell. To try it out, enter =PY( in cell F5 and add an import statement
(such as import seaborn as sns). Return a string in your code like
"Python libraries loaded". If you don't return anything, the formula
returns a Python Object of NoneType.

Library import statements in the


formula bar
Next, learn about plots. Next Step
Formula
Try here!
smodels, matplotlib,
by default

rted by default. GOOD TO KNOW: By default, single cel


GOOD TO KNOW
By default, single cell references are
tion by selecting converted to their scalar value while multi-
cell references are converted to
DataFrames.

CHECK THIS OUT


To learn more about open-source libraries to
use with Python in Excel, visit Open-source CHECK THIS OUT: To learn more about open-sou
libraries and Python in Excel - Microsoft
Support.
NOW: By default, single cell references are converted to their scalar value while multi-cell references are conver

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.

Insert Data menu


Right-click menu

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()

Next, learn about the Python editor. Next Step


Next Step
Example data Libraries
Dates Passengers DataFrame
plot type, 01/01/49 112

01/02/49 118 Type of Plot


01/03/49 132 Plot 1
01/04/49 129
or right-click 01/05/49 121
l+Alt+Shift+C 01/06/49 135

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.

1. Go to Formulas > Python > Editor to open the Python Editor.

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

Python editor editing surface

Next, learn about useful shortcuts. Next Step


TO KNOW
also use the keyboard shortcut
lt+Shift+F2 to open the editor.
I
n
s
t

Useful keyboard shortcuts


Column B contains the shortcuts to use with Python in Excel and column C explains their actions
Shortcut
=PY
Ctrl+Alt+Shift+C
Ctrl+Alt+Shift+F9

Ctrl+Alt+Shift+M

Ctrl+Alt+Shift+P
Ctrl+Enter
Ctrl+F2
Ctrl+Shift+F5

Ctrl+Shift+U

F2

F9

Next, check out other Python in Excel resources.


eful keyboard shortcuts
contains the shortcuts to use with Python in Excel and column C explains their actions.
Action
Enables Python formulas in an Excel cell.
Changes a Python plot from an image object to linked floating plot.
Resets the Python runtime. May help resolve #BUSY! or #CONNECT!
errors.
Toggles Python formula results between Python Objects and Excel Values.

Like =PY, enables Python formulas in the current cell.


Commits Python formulas in a Python cell.
Toggles between edit mode in the cell and the formula bar.
When a cell contains a card icon, additional data is available inside
card. Ctrl+Shift+F5 opens the card to display the additional data.
Expands or collapses the Excel formula bar to view more or fewer lines of
code.
Toggles between Enter mode and Edit mode in a Python cell. Edit mode
allows you to edit the Python formula, and Enter mode allows you to
select additional cells or ranges with your keyboard.
When a workbook is in Manual or Partial calculation mode, F9 recalculates
the workbook.

heck out other Python in Excel resources. Next Step


I
n
s
t

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.

Beginner level LinkedIn Learning course


#VALUE!

Get started with Python in Excel help article


#VALUE!

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

hers and they can


ny set up.
ed in Python in Excel!

You might also like