Forum Discussion
Python Script in Power Query Function
- 10 months ago
It was a long walk, but copilot and I figured it out:
let
RunPythonWithParams =
(dataset as table, divider_col as text, divider_options as text, data_type as text) =>
let
divider_col_table = #table({"Value"}, {{divider_col}}),
divider_options_table = #table({"Value"}, {{divider_options}}),
data_type_table = #table({"Value"}, {{data_type}}),PythonCode = "
import sys, os
import pandas as pd# Extract scalar values
divider_col = divider_col['Value'][0]
divider_options = divider_options['Value'][0]
data_type = data_type['Value'][0]# Add your module path
module_directory = os.path.abspath(r'C:\\xxx')
if module_directory not in sys.path:
sys.path.append(module_directory)# Import your function
from utils import anova_one# Run the analysis
output = anova_one(dataset, divider_col, divider_options, data_type)# Ensure the result is a DataFrame
if isinstance(output, pd.DataFrame):
result = output
else:
result = pd.DataFrame({'Error': ['anova_one did not return a DataFrame']})# Return named output
{'result': result}
",Py = Python.Execute(
PythonCode,
[
dataset = dataset,
divider_col = divider_col_table,
divider_options = divider_options_table,
data_type = data_type_table
]
),
Output = Py{[Name = "result"]}[Value]
in
Output
in
RunPythonWithParams
That gave me this:
It's probably because divider_col, and the following variables are strings.
Thank you for your help!
It was a long walk, but copilot and I figured it out:
let
RunPythonWithParams =
(dataset as table, divider_col as text, divider_options as text, data_type as text) =>
let
divider_col_table = #table({"Value"}, {{divider_col}}),
divider_options_table = #table({"Value"}, {{divider_options}}),
data_type_table = #table({"Value"}, {{data_type}}),
PythonCode = "
import sys, os
import pandas as pd
# Extract scalar values
divider_col = divider_col['Value'][0]
divider_options = divider_options['Value'][0]
data_type = data_type['Value'][0]
# Add your module path
module_directory = os.path.abspath(r'C:\\xxx')
if module_directory not in sys.path:
sys.path.append(module_directory)
# Import your function
from utils import anova_one
# Run the analysis
output = anova_one(dataset, divider_col, divider_options, data_type)
# Ensure the result is a DataFrame
if isinstance(output, pd.DataFrame):
result = output
else:
result = pd.DataFrame({'Error': ['anova_one did not return a DataFrame']})
# Return named output
{'result': result}
",
Py = Python.Execute(
PythonCode,
[
dataset = dataset,
divider_col = divider_col_table,
divider_options = divider_options_table,
data_type = data_type_table
]
),
Output = Py{[Name = "result"]}[Value]
in
Output
in
RunPythonWithParams