Python.Execute
The data frames a Python script leaves behind, as a navigation table: the script runs in this computer's Python.
Group: Python and R. Power Query M has it too: a query that uses it is written as in Power BI.
Syntax
Python.Execute(script as text, optional arguments as nullable record) as table
| Parameter | Type | Description |
|---|---|---|
script | text | The Python script. |
arguments | nullable record optional | Tables to hand to the script: each field becomes a pandas data frame of that name, as Power BI's dataset. |
Returns
table. Name and Value: a row per pandas data frame the script leaves, Value its table.
Remarks
- The script runs in a folder of its own, with pandas already imported as pd. Every variable that holds a data frame when it ends is a row, named after the variable; a frame with an index of its own gets the index as columns.
- It needs Python with pandas and pyarrow. OpenBI finds the newest Python installed (python.org's, the Python install manager's, Anaconda's), or the one set in OpenBI Studio's options.
- A script runs only once the project allows it: OpenBI Studio asks once per project before its scripts run. Without that, the step stops with a message saying scripts are off.
- A script that fails stops the step with the end of what it printed (its traceback). A script may run for 30 minutes at most.
- Python and R scripts are kept so that Power BI projects open and refresh. For analysis, OpenBI's notebooks are the place (Why no Python or R, in the docs).
Examples
A data frame made by the script
The result is a navigation table with one row, shops, whose Value is the frame as a table.
Python.Execute("import pandas as pd#(lf)shops = pd.DataFrame({'Shop': ['Oslo', 'Bergen'], 'Sales': [120.5, 95.0]})")
Result: not shown here: the docs' build runs no scripts.
A step's table, changed by the script
Power BI's Run Python script step writes this: the table goes in as dataset and comes back with a new column, Total (120 for the chairs, 46.5 for the lamps).
let
Source = #table(type table [Product = text, Qty = Int64.Type, Price = number], {{"Chair", 2, 60}, {"Lamp", 3, 15.5}}),
Run = Python.Execute("dataset['Total'] = dataset['Qty'] * dataset['Price']", [dataset = Source])
in
Run{[Name = "dataset"]}[Value]
Result: not shown here: the docs' build runs no scripts.