Power BI and Python: Extending Your Reports with Custom Analytics
· Power BI
Set up Python with Power BI, then put it to work: data cleaning in Power Query, matplotlib and seaborn visuals, and scikit-learn models scoring your data inside reports.
Power BI's native engine covers aggregation and filtering well — but the moment a client asks for an ARIMA forecast inside the report, or churn scores sitting next to the revenue numbers, you are at the edge of what DAX was built for. That is exactly where Python earns its seat at the table.
This guide covers the full integration: wiring up a Python environment, transforming data in Power Query with pandas, drawing charts with matplotlib and seaborn, and running scikit-learn models that score your data on every refresh.
What You'll Learn
After completing this guide, you'll integrate Python with Power BI to create custom visualizations, perform advanced analytics, and implement machine learning predictions directly in your reports. You'll set up a Python environment, write transformation scripts, and deploy Python-powered visuals.
Prerequisites
- Power BI Desktop installed
- Basic understanding of Power BI data models and DAX
- Python 3.9 or later installed on your computer
- Administrator rights to install Python packages
- 30-45 minutes for setup and testing
Python Integration Points in Power BI
You can use Python in Power BI in these ways:
| Integration Point | Purpose | When to Use |
|---|---|---|
| Python script data source | Transform or generate data in Power Query | Complex data cleaning, statistical transformations |
| Python visuals | Render static plots with matplotlib and seaborn | Statistical charts where an image is acceptable |
| Upstream Python or Fabric notebooks | Prepare and persist scored or transformed tables outside the report | Managed pipelines feeding the semantic model |
| Machine learning integration | Score data using Python-trained ML models | Predictions, clustering, anomaly detection |
Complete Setup Guide
Step 1: Install Python
Download Python 3.9 or later from python.org. On Windows, select "Add Python to PATH" during installation. For enterprise environments, consider using Anaconda distribution which includes data science packages.
Step 2: Create a Virtual Environment
Virtual environments isolate Python packages per project, preventing conflicts:
# Open Command Prompt or PowerShell
python -m venv C:\PowerBI_Python
# Activate the environment
C:\PowerBI_Python\Scripts\activate
# Verify activation (should show environment path)
where python
Step 3: Install Required Libraries
# Core data libraries
pip install pandas numpy
# Visualization libraries
pip install matplotlib seaborn plotly
# Machine learning
pip install scikit-learn statsmodels
# Optional: Statistical analysis
pip install scipy pandas-profiling
Step 4: Configure Power BI Desktop
- Open Power BI Desktop
- Go to File > Options and settings > Options
- Under "Python scripting," set the Python home directory to your virtual environment path
- Verify detected Python libraries appear
- Restart Power BI Desktop
Data Transformation with Python (Pandas)
Python scripts in Power Query excel at transformations that are complex or impossible in M:
Example 1: Advanced Data Cleaning
import pandas as pd
import numpy as np
# dataset is automatically available from Power BI
df = dataset.copy()
# Remove duplicates keeping latest record
df = df.sort_values('TransactionDate', ascending=False)
df = df.drop_duplicates(subset=['CustomerID', 'ProductID'], keep='first')
# Handle missing values intelligently
df['UnitPrice'] = df['UnitPrice'].fillna(df.groupby('ProductCategory')['UnitPrice'].transform('median'))
df['Discount'].fillna(0, inplace=True)
# Create calculated columns
df['Revenue'] = df['Quantity'] * df['UnitPrice'] * (1 - df['Discount'])
df['ProfitMargin'] = np.where(df['Revenue'] > 0,
df['Profit'] / df['Revenue'] * 100,
0)
# Extract date components
df['TransactionDate'] = pd.to_datetime(df['TransactionDate'])
df['YearMonth'] = df['TransactionDate'].dt.to_period('M')
df['DayOfWeek'] = df['TransactionDate'].dt.day_name()
df['IsWeekend'] = df['TransactionDate'].dt.dayofweek.isin([5, 6])
# Power Query discovers pandas DataFrame variables; print is only diagnostic
print(df)
Example 2: Statistical Outlier Detection
import pandas as pd
import numpy as np
from scipy import stats
df = dataset.copy()
# Z-score method for outlier detection
z_scores = np.abs(stats.zscore(df['Amount'].dropna()))
outlier_threshold = 3
df['IsOutlier'] = False
valid_amounts = df['Amount'].dropna()
df.loc[valid_amounts.index[z_scores > outlier_threshold], 'IsOutlier'] = True
# IQR method (more robust for skewed data)
Q1 = df['Amount'].quantile(0.25)
Q3 = df['Amount'].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
df['OutlierIQR'] = (df['Amount'] < lower_bound) | (df['Amount'] > upper_bound)
df['AmountCapped'] = df['Amount'].clip(lower=lower_bound, upper=upper_bound)
print(df)
Python Visualization Examples
Example 1: Matplotlib - Custom Bar Chart with Annotations
import matplotlib.pyplot as plt
import numpy as np
# dataset is provided by Power BI
categories = dataset['Category'].values
values = dataset['Sales'].values
target = dataset['Target'].mean()
# Create figure with specific styling
fig, ax = plt.subplots(figsize=(12, 6))
# Color bars based on performance vs target
colors = ['#22c55e' if v >= target else '#ef4444' for v in values]
bars = ax.bar(categories, values, color=colors, edgecolor='white', linewidth=0.5)
# Add value labels on bars
for bar, val in zip(bars, values):
height = bar.get_height()
label_text = "quot; + "{:,.0f}".format(val)
ax.text(bar.get_x() + bar.get_width()/2., height + max(values)*0.02,
label_text, ha='center', va='bottom', fontsize=9)
# Add target line
target_label = "Target: quot; + "{:,.0f}".format(target)
ax.axhline(y=target, color='#1f2937', linestyle='--', linewidth=2, label=target_label)
ax.set_title('Sales by Category vs Target', fontsize=14, fontweight='bold')
ax.set_ylabel('Sales ($)')
ax.legend()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.tight_layout()
plt.show()
Example 2: Seaborn - Correlation Heatmap
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = dataset.copy()
# Select numeric columns for correlation
numeric_cols = df.select_dtypes(include=[np.number]).columns
corr_matrix = df[numeric_cols].corr()
# Create mask for upper triangle
mask = np.triu(np.ones_like(corr_matrix, dtype=bool))
# Create heatmap
fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(corr_matrix, mask=mask, annot=True, fmt='.2f',
cmap='RdBu_r', center=0, vmin=-1, vmax=1,
square=True, linewidths=0.5,
cbar_kws={"shrink": 0.8, "label": "Correlation"})
ax.set_title('Feature Correlation Matrix', fontsize=14, fontweight='bold', pad=20)
plt.tight_layout()
plt.show()
Example 3: Seaborn - Violin Plot for Distribution Analysis
import seaborn as sns
import matplotlib.pyplot as plt
df = dataset.copy()
# Create violin plot with box plot overlay
fig, ax = plt.subplots(figsize=(14, 7))
sns.violinplot(x='Region', y='SalesAmount', hue='Quarter', data=df,
palette='Set2', inner='box', split=False, ax=ax)
# Add mean markers
sns.stripplot(x='Region', y='SalesAmount', hue='Quarter', data=df,
dodge=True, marker='D', size=3, color='black', alpha=0.5, ax=ax)
ax.set_title('Sales Distribution by Region and Quarter', fontsize=14, fontweight='bold')
ax.set_xlabel('Region')
ax.set_ylabel('Sales Amount ($)')
ax.legend(title='Quarter', bbox_to_anchor=(1.05, 1), loc='upper left')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.tight_layout()
plt.show()
Example 4: Plotly scatter for a notebook, not a Python visual
import plotly.express as px
import plotly.graph_objects as go
df = dataset.copy()
# Create interactive scatter plot
fig = px.scatter(df,
x='CustomerTenure',
y='TotalSpend',
size='OrderCount',
color='Segment',
hover_name='CustomerName',
hover_data=['Region', 'LastPurchase'],
title='Customer Value Analysis',
labels={'CustomerTenure': 'Customer Tenure (months)',
'TotalSpend': 'Total Spend ($)'},
color_discrete_sequence=px.colors.qualitative.Set1)
# Add quadrant lines
fig.add_hline(y=df['TotalSpend'].median(), line_dash="dash", line_color="gray")
fig.add_vline(x=df['CustomerTenure'].median(), line_dash="dash", line_color="gray")
# Add quadrant labels
fig.add_annotation(x=df['CustomerTenure'].max()*0.8, y=df['TotalSpend'].max()*0.9,
text="Champions", showarrow=False, font=dict(size=12, color="green"))
fig.add_annotation(x=df['CustomerTenure'].max()*0.8, y=df['TotalSpend'].min()*1.1,
text="Loyal", showarrow=False, font=dict(size=12, color="blue"))
fig.update_layout(height=500, showlegend=True)
fig.show()
Example 5: Plotly dashboard for an external notebook
import plotly.graph_objects as go
from plotly.subplots import make_subplots
df = dataset.copy()
# Create 2x2 subplot layout
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('Monthly Sales Trend', 'Sales by Category',
'Top 10 Products', 'Regional Performance'),
specs=[[{"type": "scatter"}, {"type": "pie"}],
[{"type": "bar"}, {"type": "bar"}]]
)
# Panel 1: Line chart
monthly = df.groupby('Month')['Sales'].sum().reset_index()
fig.add_trace(go.Scatter(x=monthly['Month'], y=monthly['Sales'],
mode='lines+markers', name='Sales',
line=dict(color='#2563eb', width=3)),
row=1, col=1)
# Panel 2: Pie chart
category_sales = df.groupby('Category')['Sales'].sum()
fig.add_trace(go.Pie(labels=category_sales.index, values=category_sales.values,
hole=0.3, textinfo='label+percent'),
row=1, col=2)
# Panel 3: Top products
top_products = df.groupby('ProductName')['Sales'].sum().nlargest(10).sort_values()
fig.add_trace(go.Bar(x=top_products.values, y=top_products.index,
orientation='h', marker_color='#22c55e'),
row=2, col=1)
# Panel 4: Regional performance
regional = df.groupby('Region')['Sales'].sum().sort_values(ascending=False)
fig.add_trace(go.Bar(x=regional.index, y=regional.values,
marker_color='#f59e0b'),
row=2, col=2)
fig.update_layout(height=700, showlegend=False, title_text="Sales Dashboard")
fig.show()
The two Plotly examples above are external notebook examples. Calling fig.show() does not embed Plotly's interactive HTML in a Power BI Python visual. For interactive charts within Power BI, prefer native visuals or Deneb and Vega-Lite.
Machine Learning Integration with scikit-learn
The examples below demonstrate modelling techniques, not production deployment. Do not retrain a model every time a visual renders. Train and validate upstream, save a versioned model, and score new records through an owned pipeline. A linear trend's in-sample R-squared is not evidence of forecasting accuracy; use time-ordered holdouts and compare against a simple baseline. Churn scores for training rows are not independent validation results.
Example 1: Sales Forecasting with Linear Regression
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_absolute_error
import matplotlib.pyplot as plt
df = dataset.copy()
# Prepare time series data
df['Date'] = pd.to_datetime(df['Date'])
df = df.sort_values('Date')
df['DayNumber'] = (df['Date'] - df['Date'].min()).dt.days
# Aggregate to monthly
monthly = df.groupby(df['Date'].dt.to_period('M')).agg({
'Sales': 'sum',
'DayNumber': 'first'
}).reset_index()
monthly['MonthIndex'] = range(len(monthly))
# Train model
X = monthly[['MonthIndex']].values
y = monthly['Sales'].values
model = LinearRegression()
model.fit(X, y)
# Predict next 6 months
future_months = np.arange(len(monthly), len(monthly) + 6).reshape(-1, 1)
predictions = model.predict(future_months)
# Model performance
r2 = r2_score(y, model.predict(X))
print(f"Model R² Score: {r2:.3f}")
print(f"Coefficient: {model.coef_[0]:.2f} sales/month")
print(f"Predictions: {predictions}")
# Visualize
plt.figure(figsize=(12, 6))
plt.plot(monthly['MonthIndex'], y, 'b-o', label='Actual', markersize=8)
plt.plot(monthly['MonthIndex'], model.predict(X), 'g--', label='Fit', linewidth=2)
plt.plot(future_months.flatten(), predictions, 'r--o', label='Forecast', markersize=8)
plt.xlabel('Month')
plt.ylabel('Sales ($)')
plt.title('Sales Forecast using Linear Regression')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Example 2: Customer Segmentation with K-Means Clustering
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import seaborn as sns
df = dataset.copy()
# Prepare features for clustering
features = df[['TotalSpend', 'OrderFrequency', 'AvgOrderValue', 'DaysSinceLastOrder']].copy()
# Standardize features
scaler = StandardScaler()
features_scaled = scaler.fit_transform(features)
# Find optimal clusters using elbow method
inertias = []
K_range = range(2, 11)
for k in K_range:
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
kmeans.fit(features_scaled)
inertias.append(kmeans.inertia_)
# Apply K-Means with chosen number of clusters
optimal_k = 4 # Adjust based on elbow plot
kmeans = KMeans(n_clusters=optimal_k, random_state=42, n_init=10)
df['CustomerSegment'] = kmeans.fit_predict(features_scaled)
# Segment profiling
segment_profiles = df.groupby('CustomerSegment').agg({
'TotalSpend': ['mean', 'sum', 'count'],
'OrderFrequency': 'mean',
'AvgOrderValue': 'mean'
}).round(2)
# Visualize clusters using PCA
pca = PCA(n_components=2)
features_pca = pca.fit_transform(features_scaled)
plt.figure(figsize=(12, 8))
scatter = plt.scatter(features_pca[:, 0], features_pca[:, 1],
c=df['CustomerSegment'], cmap='viridis',
alpha=0.6, s=50)
plt.colorbar(scatter, label='Customer Segment')
pc1_var = pca.explained_variance_ratio_[0] * 100
pc2_var = pca.explained_variance_ratio_[1] * 100
plt.xlabel('PC1 ({:.1f}% variance)'.format(pc1_var))
plt.ylabel('PC2 ({:.1f}% variance)'.format(pc2_var))
plt.title('Customer Segments (PCA Projection)')
plt.tight_layout()
plt.show()
print(segment_profiles)
print(df[['CustomerID', 'CustomerSegment']])
Example 3: Anomaly Detection for Transactions
import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
df = dataset.copy()
# Features for anomaly detection
features = df[['Amount', 'Hour', 'DayOfWeek', 'MerchantCategory']].copy()
# Encode categorical variables
features = pd.get_dummies(features, columns=['MerchantCategory'], drop_first=True)
# Scale features
scaler = StandardScaler()
features_scaled = scaler.fit_transform(features)
# Train Isolation Forest
iso_forest = IsolationForest(contamination=0.05, random_state=42, n_estimators=100)
df['AnomalyScore'] = iso_forest.fit_predict(features_scaled)
df['IsAnomaly'] = df['AnomalyScore'] == -1
df['AnomalyProbability'] = -iso_forest.decision_function(features_scaled)
# Normalize anomaly score to 0-1
df['AnomalyProbability'] = (df['AnomalyProbability'] - df['AnomalyProbability'].min()) / (df['AnomalyProbability'].max() - df['AnomalyProbability'].min())
# Summary statistics
anomaly_count = df['IsAnomaly'].sum()
total_count = len(df)
print(f"Detected {anomaly_count} anomalies out of {total_count} transactions ({anomaly_count/total_count*100:.2f}%)")
print(f"\nAnomalous transactions:")
print(df[df['IsAnomaly']][['TransactionID', 'Amount', 'Merchant', 'AnomalyProbability']].head(10))
Example 4: Classification for Churn Prediction
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score
import matplotlib.pyplot as plt
import seaborn as sns
df = dataset.copy()
# Prepare features and target
X = df[['Tenure', 'MonthlyCharges', 'TotalCharges', 'NumSupportTickets',
'ContractLength', 'PaymentMethod']].copy()
X = pd.get_dummies(X, drop_first=True)
y = df['Churned']
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)
# Train model with class balancing
rf_model = RandomForestClassifier(n_estimators=100, max_depth=10,
class_weight='balanced', random_state=42)
rf_model.fit(X_train, y_train)
# Predictions and probabilities
y_pred = rf_model.predict(X_test)
y_prob = rf_model.predict_proba(X_test)[:, 1]
# Add predictions to original data for Power BI
df['ChurnProbability'] = rf_model.predict_proba(X)[:, 1]
df['PredictedChurn'] = df['ChurnProbability'] > 0.5
df['RiskCategory'] = pd.cut(df['ChurnProbability'],
bins=[0, 0.3, 0.6, 1.0],
labels=['Low', 'Medium', 'High'])
# Feature importance
feature_imp = pd.DataFrame({
'Feature': X.columns,
'Importance': rf_model.feature_importances_
}).sort_values('Importance', ascending=False)
print("Classification Report:")
print(classification_report(y_test, y_pred))
print(f"\nROC AUC Score: {roc_auc_score(y_test, y_prob):.3f}")
print(f"\nFeature Importance:")
print(feature_imp.head(10))
# Output scored data
print(df[['CustomerID', 'ChurnProbability', 'PredictedChurn', 'RiskCategory']])
Error Handling and Performance Considerations
Robust Error Handling
import pandas as pd
import numpy as np
import logging
# Set up logging for debugging
logging.basicConfig(level=logging.INFO)
try:
df = dataset.copy()
# Validate input data
if df.empty:
raise ValueError("Dataset is empty")
required_columns = ['Date', 'Amount', 'Category']
missing_cols = [col for col in required_columns if col not in df.columns]
if missing_cols:
raise ValueError(f"Missing required columns: {missing_cols}")
# Type checking and conversion
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Amount'] = pd.to_numeric(df['Amount'], errors='coerce')
# Handle conversion failures
invalid_dates = df['Date'].isna().sum()
if invalid_dates > 0:
logging.warning(f"Found {invalid_dates} invalid dates, dropping rows")
df = df.dropna(subset=['Date'])
# Process data
df['MonthYear'] = df['Date'].dt.to_period('M')
df['Amount_Cleaned'] = df['Amount'].clip(lower=0)
# Aggregate with error handling
summary = df.groupby('MonthYear').agg({
'Amount_Cleaned': ['sum', 'mean', 'count']
}).reset_index()
summary.columns = ['MonthYear', 'TotalAmount', 'AvgAmount', 'TransactionCount']
logging.info(f"Successfully processed {len(df)} records")
print(summary)
except ValueError as e:
logging.error(f"Data validation error: {e}")
# Return empty dataframe with expected columns
print(pd.DataFrame({'Error': [str(e)], 'Processed': [False]}))
except Exception as e:
logging.error(f"Unexpected error: {type(e).__name__}: {e}")
print(pd.DataFrame({'Error': [str(e)], 'Processed': [False]}))
Performance Optimization
- Data sampling: For exploration, sample large datasets:
df_sample = df.sample(n=10000) - Vectorized operations: Always use pandas vectorized operations over Python loops
- Data type optimization: Convert string columns to categorical when appropriate
- Chunked processing: Process large files in chunks:
pd.read_csv('file.csv', chunksize=10000) - Caching: Cache intermediate results in Dataflows for repeated transformations
Real-World Use Cases
1\. Demand Forecasting
Combine Power BI's data connectivity with Python's time series libraries (statsmodels, Prophet) to create accurate demand forecasts that auto-update with your refresh schedule.
2\. Customer Churn Prediction
Score customers using ML models built in Python, then display churn probability in Power BI with conditional formatting to highlight at-risk accounts.
3\. Anomaly Detection
Flag unusual transactions, system metrics, or business patterns using isolation forests or autoencoders, visualizing anomalies with custom Python visuals.
4\. Text Analytics
Perform sentiment analysis, topic modeling, or keyword extraction on customer feedback using NLTK or spaCy, then aggregate results in Power BI dashboards.
5\. Clustering and Segmentation
Apply K-means or hierarchical clustering to segment customers, products, or markets, creating dynamic cluster visualizations that update with your data.
Python in Power BI versus Fabric notebooks
Keep lightweight pandas transformations in Power Query when the refresh path is manageable. Put repeatable training, dependency-heavy scoring and shared pipelines upstream, for example in a Fabric notebook if your organisation uses Fabric. Persist the scored output and let Power BI read it as a table.
This separates model training from report interaction and lets you record model version, scoring date and validation results. It also avoids presenting a slicer-driven retraining exercise as a stable business prediction.
Service Python visuals use a supported package list, not your local environment. Microsoft currently lists Python 3.11 for Premium/Fabric-backed workspaces; verify the live package reference rather than assuming the newest Desktop Python version is the hosted runtime. The service blocks networking for these visuals.
For refresh with Python steps, consult the personal gateway guidance. Review privacy settings with the data owner; do not relax them blindly to make a script run.
Limitations and Considerations
- Memory constraints: Python visuals load all data into memory; for large datasets, pre-aggregate in DAX first
- Refresh timing: Python scripts add time to dataset refresh; monitor and optimize
- Production dependencies: Python libraries must be available on refresh machines (gateway for on-premises sources)
- No streaming: Python visuals don't support real-time streaming datasets
- Certification: Python visuals cannot be certified for AppSource distribution
Troubleshooting Common Issues
Python Visual Not Rendering
Symptoms: Blank visual or error message when you add a Python visual.
Solutions:
- Verify Python is installed and the path is correct in Power BI's options
- Check that required packages (matplotlib, pandas) are installed in your Python environment
- Look at the Python visual's error pane for specific error messages
- Test your Python script outside Power BI in a Jupyter notebook first
- Ensure the script creates a supported plot and calls matplotlib.pyplot.show(); printing a DataFrame alone does not render a chart
Python Script Fails in Power Query
Symptoms: Error when running Python script in Power Query Editor.
Solutions:
- Check that your Python environment has pandas installed:
pip install pandas - Ensure the script leaves its output in a pandas DataFrame variable, then select that table in Power Query
- Verify data types match what Power BI expects
- Check for missing values that might cause conversion errors
- Use try-except blocks to handle errors gracefully
Slow Performance with Python Visuals
Symptoms: Visual takes more than 10 seconds to render, report feels sluggish.
Solutions:
- Pre-aggregate data in DAX measures before sending to Python
- Use vectorized pandas operations instead of Python loops
- Limit data to under 50,000 rows for Python visuals
- Consider using Power BI's native visuals when possible
- Cache intermediate results if using the same transformation multiple times
Frequently Asked Questions
1\. Can I use Python visuals in Power BI Service?
Python visual rendering and Python data-refresh execution are separate paths. The service renders supported Python plots with its managed packages. Python steps in Power Query require the supported personal-mode gateway setup for scheduled refresh, with Python and dependencies installed on that machine. Do not assume a Premium workspace alone runs arbitrary Python refresh scripts.
2\. How do I handle Python library version conflicts?
Use virtual environments for each project. Document your dependencies in a requirements.txt file. For enterprise deployments, consider using Docker containers or Anaconda environments managed by IT.
3\. What's the maximum data size for Python visuals?
Power BI limits Python visuals to approximately 150,000 rows. For larger datasets, aggregate in DAX measures first, or use Python script visuals to process data and output a smaller summary.
4\. Can I use Python libraries not installed by default?
In Desktop, you can install packages into the selected local environment. The service uses Microsoft's supported package list; your administrator cannot simply pip-install private packages into its managed visual runtime. Check package and version compatibility before publishing.
5\. How do I debug Python scripts in Power BI?
First, test your scripts outside Power BI in a Jupyter notebook or IDE. In Power BI, check the Python script visual's error messages carefully—they often show line numbers. Use logging statements and try-except blocks to capture errors. The Power Query Editor shows Python script errors when editing queries.
Related guides and help
- Visuals without Python dependencies: Deneb custom visuals in Power BI
- Python directly in spreadsheets: Python in Excel guide
- Get the model right first: Power BI data modelling best practices
Need forecasting, anomaly detection or custom analytics added to an existing report? See the Power BI service or get in touch.