0% found this document useful (0 votes)
14 views

Tutorial Python Msa

Guía Python

Uploaded by

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

Tutorial Python Msa

Guía Python

Uploaded by

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

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
needed. Just type Python in a cell, and calculations run securely in the Microsoft Clou
including 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
>
cel
c
o
n
tI
in
n
s
u
t

Become familiar with Python (=PY


e

o
n

t
1. To write or edit Python code, you need to make sure you're using a Python
formula. To do so, go to Formulas > Python and select Insert Python, or enter
o
=PY into a cell and select PY from the formula AutoComplete menu. You can also
enter =PY( in a cell to automatically select the PY function.
t
h
e

n
e
x
t
Formulas > Python
s
Go
e to cell I5 and I9 to learn more about samples and the PY function, or go to cell B7 to continue on.
c 2. You don't need to install Python on your computer to use this feature. All Python
t runs securely in the Microsoft Cloud.
i
o
n 3. You can see a change in the cell and formula bar when Python is enabled. This
: helps distinguish when you're writing or editing a Python formula. To commit Python
code, you must first always enable the Python formula.
e
d
i
t
i Python in Excel cell
n badge
g Formula bar Python in Excel
. badge

Next, learn more about editing. Next Step


on (=PY)

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. CHECK THIS OUT:
Select Insert Python button in the Formulas tab to v

CHECK THIS OUT: To learn more about =PY, visit htt

CHECK THIS OUT


To learn more about =PY, visit PY function - Microsoft Support.
the Formulas tab to view Tips and Samples to help you get started with Python in Excel.

e about =PY, visit https://support.microsoft.com/office/py-function-31d1c523-fb13-46ab-96a4-d1a90a9e512f


6a4-d1a90a9e512f
I
n
s
t

Learn how to edit a Python form


1. In cell D4, enter =PY( to enable Python in the cell, and then enter "1+1".
Unlike regular
Excel formulas, you need to use Ctrl+Enter to commit changes.
Column D is to input the Python formula.

Editing a Python
formula

2. Cell D4 returns the value 2 as a Python object, one of two Python output types.
Select the card icon within the cell to learn more about Python objects.

C
o
l 3. Excel value is the second Python output type. Use the controls next to the
u formula or in the right-click menu to adjust the output type.

Right-click menu
Next to formula bar

Go to cell O3 to learn the keyboard shortcut to toggle between output types or go to cell B17 to contin
4. In cell D7, enter =PY( and then "1+1". This time, change the output to an Excel
value.
Go to cell L8 to learn about where you can edit a Python formula or go to the next tab to continue on t
Next, learn about cell references. Next Step
the cell
or the
formula
bar.
While
editing,
GOOD TO KNOW use the
keyboar
The default output type is a Python
d
n form
Formula Expected result
object.
shortcut
You can use the keyboard shortcut
Ctrl+F2
Try here! The value 2 as a Python object. Ctrl+Alt+Shift+M to toggle betwee
to
output types.
toggle
betwee
n the
cell and
Try here! The value 2 as an Excel value. formula
bar.

CHECK THIS OUT


You can edit the formula in either the cell or
the formula bar. While editing, use the
keyboard shortcut Ctrl+F2 to toggle
between the cell and formula bar.
NOW
utput type is a Python

he keyboard shortcut GOOD TO KNOW: The default output type is a Python object. You can use the keybo
ift+M to toggle between
ct. You can use the keyboard shortcut Ctrl+Alt+Shift+M to toggle between output types.
I
n
s
t

C
e
l
l

C
e
G
lo
l
t
Reference cells to bring data into
To protect your security, common functions used to import data in Python (like
as pandas.read_csv and pandas.read_excel) aren’t compatible with Python in Excel. To import
use an Excel worksheet or a Power Query data source.

To import data from an Excel worksheet, use the xl() function for Python in Excel.
This function takes two parameters, a reference string pointing to data
in Excel, and an optional parameter to adjust how headers are treated. Examples: xl("A1"),
xl("A1", headers=True), and xl("$A$1:$D$10", headers=False).

1. To start, take a look at DataFrames created from the example data in cells D4 to F10.
Cell H5 is a DataFrame as a Python object and L5 is a DataFrame as Excel values.
Inspect or play around with the reference and headers parameters. Note: Multi-cell
references (or ranges) like A1:C5 are treated by default as pandas DataFrame objects.

2. To create a new Excel reference while in a Python cell, select the data on the grid that
you'd like to use. If you prefer to use the keyboard, use F2 to toggle between Enter mode
and Edit mode in Python cells, and then use your arrow keys to select cells or ranges.
Don't forget to type =PY( first!

3. Give it a try! In cells H15 and L15, create new DataFrames using the Income and Spend
data. Set H15 to be a Python object and set L15 to Excel values. Note: If you reference an
Excel table, you need to include the full structured table reference: =PY(xl("Table1[#All]").
Give this a try in cells H28 and L28.

Next, learn about external data. Next Step


to Py Example data Example: as Python object
Category Product Sales
Accessories Helmets $8,300 #VALUE!
mport data, Accessories Tires and Tube $8,700
Bikes Road Bikes $3,500
Bikes Mountain Bikes $3,100
Components Pedals $800
Components Wheels ###

Try it out! Range Set to Python object

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 object

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 GOOD TO KNOW
9 199 162 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
10 168 174
> Right arrow > Down
arrow.

GOOD TO KNOW: To select the entire table using your keyb


Example: as Excel values

Category Product Sales


Accessories Helmets 8300
Accessories Tires and Tubes 8700
Bikes Road Bikes 3500
Bikes Mountain Bikes 3100
Components Pedals 800
Components Wheels ###

Set to Excel values

Try here!

Set to Excel values

Try here!

ble using
trl+Shift
wn
ble using
trl+Shift
wn

ntire table using your keyboard, use Ctrl+Shift > Right arrow > Down arrow.
I
n
s
t
Go to the next tab to continue on to the next section: diagnostics.
Use Power Query to import extern
To use data from external sources, go to Data > Get Data. The Get Data feature uses Power
Query. With Power Query you can import data from multiple sources, including CSV files. Every
import creates a new query. For more information on how to use Power Query, visit aka.ms/pqxl.

Note: If you have existing workbooks with Power Query queries, start with step 6.

1. For this example, you'll import data from the Northwind OData service, a test data source.
First, copy the following link to the Northwind OData service so that you can use it in step 2:
https://services.odata.org/northwind/northwind.svc/

2. Go to Data > Get Data > From Other Sources > From OData Feed. In the dialog that
appears, paste the link copied from step 1, then select OK.

3. In the Navigator dialog that appears next, you'll select a data table to load into Excel.
Select the Categories table, then Load To... under the Load menu.

Power Query Navigator


4. After loading the data, the Import Data dialog appears. Choose Only Create Connection
and then OK to establish a data connection from the source. Power Query automatically
creates a query for this connection.

Import Data dialog

5. Next, the Queries & Connections pane appears in your workbook. It lists the connection
you made to the Categories table from the Northwind OData service. If you had other
queries or connections, they would also appear here. You can always open the pane
by going to Data > Queries & Connections.

6. To import the external data into Python, create a DataFrame by using the xl()
function. After following steps 1 - 5 to create the connection or using an already established
connection, create a new DataFrame in cell D5 by referencing the name of the Power Query
connection. To create a DataFrame with the Categories 'table from the Northwind Odata
service, enter: =PY(xl("Categories").

Go to the next tab to continue on to the next section: diagnostics.


Next, learn about diagnostics. Next Step
ernal data
Formula Expected result
Try here! DataFrame
I
n
s
t

See errors and outputs in the diag


1. Standard output (stdout) and standard error (stderr) results are returned to
the Diagnostics
task pane. The task pane opens automatically for errors or print statements. You can also
open the diagnostics pane by right-clicking a Python cell and selecting Show Diagnostics in
the menu, or by going to Formulas > Python (Preview) > Diagnostics. If you don't want
the pane to open automatically, uncheck "Show automatically" at the bottom of the
task pane.
C
o2. In cells D6 and D8, insert a Python formula with the code below to see how it
lworks.
uCell D6: 1/0
Cell D8: print("Hello world!")
You should see both an error and print statement in the diagnostics pane for cells D6
and D8.

G
o
Next, learn about calculation order. Next Step
t
he diagnostics pane
Example Expected result
ou can also Try here! #PYTHON! error because you cannot divide by 0
Diagnostics in
you don't want Try here! NoneType ("Hello world!" will be printed in the
Diagnostics pane.)
I
n
s
t

Cells D6 to E10 contain data with 2 columns. One for Widget, and one for Sales.

C
o
l
u

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 last expression. If None is returned, you
see
a Python object of NoneType in a cell. In cell H6, enter the following code in a single Python
formula to see how it works:
1+1
print("Hello world!")

2. Python in Excel cells calculate in row-major order, across a row from left-to-right
(from column
A to column XFD) and then across each following row down the worksheet. Let's see how
this works with an example. In cell H10 there's a DataFrame named df containing the
Widget Sales sample data. Now, try and run the Python code "df['Sales'].sum()" in both cell
H8 and cell H12. In H8 you get a #PYTHON! error because df hasn't been defined yet. In H12
the code works as expected because H10 precedes H12 in the calculation order.

GOOD
For lang
3. In addition to the diagnostics pane, you can view error messages in a dialog. First, Python
select the icon that appears when selecting a cell with an error. Then, select Show across a
Error Message from the menu. A Python error message dialog displays.

Error message dialog

Error menu

4. The calculation order concept also applies across worksheets within a workbook,
based on the order of worksheets from left-to-right. Global variables can be used

across worksheets, calculating based on the order of the worksheets.

Next, learn about Python errors. Next Step


on order
Example data Example Expected value
ngle Python Widget Sales Try here! NoneType Python object returned since that
Foo 5
Bar 6 Try here! #PYTHON! error because DataFrame is defin
Baz 7 GOOD TO
Try here! KNOW: For
Boo 8 DataFrame
languages
that read
Try here! right-to-left,
Correct sum (26) because DataFrame is refe
Python cells
and
" in both cell worksheets
d yet. In H12 calculate
across a row
from right-to-
left.
GOOD TO KNOW
For languages that read right-to-left,
Python cells and worksheets calculate
across a row from right-to-left.
ct returned since that is the last expression.

se DataFrame is defined below in F7.

use DataFrame is referenced in cell F7 above.


I
n
s
t

Understand a few errors


1. #BUSY!: This displays when a Python formula is calculating.
2. #PYTHON!: This error displays when there's an issue with the Python code. By
default, the
Diagnostics pane automatically opens with more details on the error.
To see how this works, select cell D6, enable Python in the cell, enter "1/0", and commit
the formula. You should see a #PYTHON! Error alongside the diagnostics pane with more
information. You can also select the error icon next to the cell and then select Show
Error Message from the menu.
Cell F6 explains the expected result from the formula in cell D6.
3. #CONNECT!: This error indicates issues with the Python cloud service. If you
see this error,
reset your Python global variables in your workbook via Formulas > Python (Preview)
> Reset, or reset the Python runtime via Formulas > Python (Preview) > Reset > Reset Run
Both will trigger recalculation unless you are in Manual recalculation mode.
G
o
Next, learn more about libraries. Next Step
t
Formula Expected result
Try here! #PYTHON!

, and commit
ane with more

GOOD TO KNOW
You can change your calculation mode through
reca
Formulas > Calculation > Calculation
lcul
Options.
ates
all
Automatic automatically recalculates all
for
dependent formulas every time you make a
mul
change in Excel. This is the default setting.
as
auto
Manual recalculates formulas when you
mati
manually trigger the process to do so.
call
y
Partial is a hybrid between manual and
exc
automatic. This mode recalculates all formulas
ept
automatically except those that are typically
thos
time consuming, like Python and Data Tables.
e
that
are
typi
call
y
time
con
sum
ing,
like
Pyth
on
and
Dat
a
Tabl
es.
on (Preview)
> Reset > Reset Runtime.

xt Step
I
n
s
t

Use Python libraries


1. Python in Excel uses a secure, open-source library distribution from Anaconda.
The following
core set of libraries are recommended: 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. Python in Excel settings and configuration details, like importing open-source
Python libraries,
are done through the Initialization pane. View the default configuration by selecting
Formulas > Python (Preview) > 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 D4 and add an import statement (such as import seaborn as
sns).
string Return
in youracode 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.
G
o
Next, learn about plots. Next Step
t
Formula
Try here!
rn, statsmodels,
e-initialized by default

ed by default. GOOD TO KNOW


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

CHECK THIS OUT: To learn more about open-source libra


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 Support.
efault, single cell references are converted to their scalar value while multi-cell references are converted to Da

e about open-source libraries to use with Python in Excel, visit https://support.microsoft.com/office/open-source


es are converted to DataFrames.

om/office/open-source-libraries-and-python-in-excel-c817c897-41db-40a1-b9f3-d5ffe6d1bf3e
I
n
s
t

G
o

t
Create Python plots
1. You can leverage powerful Python libraries to create data visualizations and plots.
Give it a
try! Modify the type of plot created in cell H8 by choosing from the dropdown options in cell H7.
You'll notice that as you switch the plot type, the code recalculates to create the appropriate
plot, and the floating image of the plot also updates automatically.

2. By default, you see a Python object returned to the cell with an Image data type. 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+C when selecting a cell with the Image data type. 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 experiment with 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 Libraries
Loaded!#NAME?
Dates Passengers DataFrame
options in cell H7. 1/1/1949 112
e appropriate 118 Type of
2/1/1949 Plot line
3/1/1949 132 Plot 1 #NAME?
4/1/1949 129

5/1/1949 121

6/1/1949 135
ard shortcut 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 Try here!
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 Try here!
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
I
n
s
t
G
o

t
Use the Excel Labs Python editor t
The Python editor is a new addition to Excel Labs that allows you to write and edit Python
formulas in
Excel, using a dedicated code editor with similar capabilities as those available in Python noteboo
environments. This is an experimental release to get early feedback, so we can develop Excel to b
useful for you. The Python editor is designed to complement the Python in Excel experience with a
editing surface optimized for more complex and longer Python code snippets.

1. Install Excel Labs. Go to Home > Add-ins in the ribbon, search for Excel Labs and select
install.
Once installed, the Excel Labs add-in displays in Home.

2. Launch Excel Labs and load the Python editor experiment. Select Open to load the editor
experience. You can choose to also make it open by default.

Select Python editor in Excel Labs

3. Give it a try! You can edit any existing formulas or create new Python formulas in the editor.
Python editor editing
surface

Next, learn about useful shortcuts.


tor to write or view code
on notebook
p Excel to be the most
ence with an
Next Step
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 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.

ck 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