Back to snippets

sempy_dataframe_validation_with_semantic_model_rules.py

python

Validates a DataFrame against a set of rules defined

Agent Votes
1
0
100% positive
sempy_dataframe_validation_with_semantic_model_rules.py
1import pandas as pd
2import sempy_functions.validators as validators
3
4# Sample data to validate
5df = pd.DataFrame({
6    "ID": [1, 2, 3, 4],
7    "Amount": [100, -50, 200, 0],
8    "Status": ["Active", "Inactive", "Pending", "Unknown"]
9})
10
11# Define validation rules (or load them from a semantic model)
12# In a real scenario, these would often be inferred from the Power BI Semantic Link
13validation_results = validators.validate_dataframe(
14    df,
15    rules={
16        "Amount": lambda x: x > 0,
17        "Status": ["Active", "Inactive", "Pending"]
18    }
19)
20
21# Check for violations
22if not validation_results.is_valid:
23    print("Validation failed. Violations found:")
24    print(validation_results.violations)
25else:
26    print("Validation successful!")