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

Python in Excel tutorial1

Uploaded by

anr111207
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Python in Excel tutorial1

Uploaded by

anr111207
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 54

W

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.

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
Suppor
3. Changes in the cell and formula bar indicate Python is enabled. You can edit the 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


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

ormulas tab to
arted with Python

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


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

Next, learn about external data. Next Step


Python Example data Example: as Python Objects
Category Product Sales
Accessories Helmets $8,300 #NAME?
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

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
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 To select the entire table using
your keyboard, use Ctrl+Shift
10 168 174 > 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 usin


Python Objects Example: as Excel Values

#NAME? #NAME? ###


#NAME? #NAME? ###
#NAME? #NAME? ###
#NAME? #NAME? ###
#NAME? #NAME? ###
#NAME? #NAME? ###

#NAME? #NAME? ###

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

Import Data dialog

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

Next, learn about calculation order. Next Step


l data
Formula Expected result
Try here! DataFrame
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 t
Foo 5
Bar 6 Try here! #PYTHON! error because DataFrame is d
Baz 7

Boo 8 #NAME? DataFrame

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

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.

ror because DataFrame is defined below in H10.

26) because 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


lcul
ates
all
for
mul
as
auto
mat
icall
y
exc
ept
thos
e
Formula Expected result
that
Try here! #PYTHON! are
typi
call
y
pane opened. tim
e
con
sum
ing,
like
Pyth
on
and
Dat
GOOD TO KNOW
a
With the Python in Excel add-on, you can Tabl
change your calculation mode through es.
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!
models, matplotlib,

ed by default. GOOD TO KNOW GOOD TO KNOW: By default, single ce


By default, single cell references are
converted to their scalar value while multi-
on by selecting
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
libraries and Python in Excel - Microsoft CHECK THIS OUT: To learn more about open-so
Support.
OW: By default, single cell references are converted to their scalar value while multi-cell references are convert

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.

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


Example data Libraries
Dates Passengers DataFrame
1/1/1949 112

2/1/1949 118 Type of Plot


3/1/1949 132 Plot 1
4/1/1949 129
right-click 5/1/1949 121
Alt+Shift+C 6/1/1949 135

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.

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

Python editor editing surface

Next, learn about useful shortcuts. Next Step


TO KNOW
also use the keyboard shortcut
t+Shift+F2 to open the editor.
l
l

B
3
.

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.


ful keyboard shortcuts
ontains 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.

eck out other Python in Excel resources. Next Step


l
l

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.

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 Exc
arning about

rs and they can

d in Python in Excel!

You might also like