Claude Code for whylogs: Data Logging and Profiling — Claude Skills 360 Blog
Blog / AI / Claude Code for whylogs: Data Logging and Profiling
AI

Claude Code for whylogs: Data Logging and Profiling

Published: September 11, 2027
Read time: 5 min read
By: Claude Skills 360

whylogs profiles datasets with lightweight statistical summaries. pip install whylogs. import whylogs as why. result = why.log(df) profiles a pandas DataFrame. profile = result.profile(). profile.view().to_pandas() shows column statistics — count, null fraction, min, max, mean, stddev, quantiles, cardinality estimate. why.log({"text": "hello world"}) profiles a single record. Save: result.writer("local").option(base_dir="profiles").write() saves .bin and .json. Read: DatasetProfileView.read("profile.bin"). WhyLabs integration: why.init(whylabs_api_key="key", org_id="org", dataset_id="model-123"), then result.writer("whylabs").write() uploads to WhyLabs for monitoring. Logger: with why.logger(mode=LoggingMode.ROLLING, interval=10, when=TimeUnit.MINUTES) as logger: logger.log({"feature": value}) for streaming. Constraint checks: from whylogs.core.constraints.factories import no_missing_values, is_non_negative, greater_than_number. builder = ConstraintsBuilder(dataset_profile_view=profile.view()). builder.add_constraint(no_missing_values(col_name="user_id")). builder.add_constraint(is_non_negative("amount_usd")). constraints = builder.build(). report = constraints.report()report is a list of (constraint_name, passed, metrics). Segments: why.log(df, schema=DatasetSchema(segments=segment_column("plan"))) profiles each segment separately. Column schema: DatasetSchema(resolvers=Resolver()) for custom metric configuration. Profile comparison: ProfileView.diff(profile_a, profile_b) detects drift. SummaryDriftAlgorithm computes standardized drift scores. Claude Code generates whylogs profiling scripts, constraint sets, streaming loggers, WhyLabs uploads, and CI pipeline checks.

CLAUDE.md for whylogs

## whylogs Stack
- Version: whylogs >= 1.4
- Profile: why.log(df) → result.profile() → profile.view().to_pandas()
- Save: result.writer("local").option(base_dir="profiles/").write()
- WhyLabs: why.init(whylabs_api_key, org_id, dataset_id) then result.writer("whylabs").write()
- Constraints: ConstraintsBuilder(profile.view()) + add_constraint / build / report
- Segments: DatasetSchema(segments=segment_column("col")) for per-segment profiles
- Logger: why.logger(mode=LoggingMode.ROLLING, interval=5, when=TimeUnit.MINUTES)
- Compare: ProfileView.diff(ref, current) for drift detection

Profiling and Constraints

# monitoring/whylogs_profiler.py — data profiling with constraints
from __future__ import annotations
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Any

import pandas as pd
import whylogs as why
from whylogs.core import DatasetSchema
from whylogs.core.constraints import ConstraintsBuilder, MetricConstraint
from whylogs.core.constraints.factories import (
    greater_than_number,
    is_in_range,
    is_non_negative,
    no_missing_values,
    smaller_than_number,
)
from whylogs.core.segmentation_partition import segment_column
from whylogs.core.view.dataset_profile_view import DatasetProfileView

FEATURE_COLS = ["age", "tenure_days", "monthly_spend", "support_tickets", "last_login_days"]
TARGET_COL   = "churned"


# ── Profile a DataFrame ───────────────────────────────────────────────────────

def profile_dataframe(
    df:           pd.DataFrame,
    output_dir:   str = "profiles",
    dataset_name: str = "churn_data",
) -> DatasetProfileView:
    """Profile a DataFrame and save to disk."""
    Path(output_dir).mkdir(exist_ok=True)
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")

    result = why.log(df)

    # Save binary profile
    result.writer("local") \
          .option(base_dir=output_dir) \
          .option(filename=f"{dataset_name}_{ts}") \
          .write()

    # Also export JSON summary
    view = result.profile().view()
    summary = view.to_pandas()
    summary.to_csv(f"{output_dir}/{dataset_name}_{ts}_summary.csv")

    print(f"Profile saved: {output_dir}/{dataset_name}_{ts}.bin")
    print(f"\nColumn statistics:")
    print(summary[["counts/n", "counts/null", "distribution/mean", "distribution/stddev",
                    "distribution/min", "distribution/max"]].to_string())
    return view


# ── Segment profiling ─────────────────────────────────────────────────────────

def profile_segments(
    df:          pd.DataFrame,
    segment_col: str = "plan",
    output_dir:  str = "profiles",
) -> dict[str, DatasetProfileView]:
    """Profile data broken down by a categorical segment."""
    result = why.log(
        df,
        schema=DatasetSchema(
            segments=segment_column(segment_col),
        ),
    )

    segment_views: dict[str, DatasetProfileView] = {}
    for segment, view in result.segments().items():
        segment_name = str(segment)
        segment_views[segment_name] = view

        # Save each segment profile
        Path(output_dir).mkdir(exist_ok=True)
        view.write(f"{output_dir}/segment_{segment_name}.bin")
        print(f"Segment '{segment_name}': {view.to_pandas()['counts/n'].values[0]} rows")

    return segment_views


# ── Build constraint set ──────────────────────────────────────────────────────

def build_constraints(view: DatasetProfileView) -> ConstraintsBuilder:
    """Define data quality constraints."""
    builder = ConstraintsBuilder(dataset_profile_view=view)

    # Completeness constraints
    builder.add_constraint(no_missing_values(col_name="age"))
    builder.add_constraint(no_missing_values(col_name="monthly_spend"))

    # Range constraints
    builder.add_constraint(is_in_range(col_name="age",           lower=18,    upper=120))
    builder.add_constraint(is_in_range(col_name="monthly_spend", lower=0,     upper=100000))
    builder.add_constraint(is_in_range(col_name="tenure_days",   lower=0,     upper=3650))
    builder.add_constraint(is_non_negative("support_tickets"))
    builder.add_constraint(is_non_negative("last_login_days"))

    # Distribution constraints (warn if mean drifts)
    builder.add_constraint(
        is_in_range(col_name="monthly_spend", lower=10, upper=5000,
                    metric_selector=lambda m: m.mean)
    )

    return builder


def check_data_quality(
    df:         pd.DataFrame,
    fail_fast:  bool = False,
) -> tuple[bool, list[dict]]:
    """Profile data and run constraint checks. Returns (all_passed, report)."""
    view     = profile_dataframe(df)
    builder  = build_constraints(view)
    constraints = builder.build()
    report      = constraints.report()

    failures = []
    for constraint_name, passed, metric_value in report:
        status = "PASS" if passed else "FAIL"
        print(f"  {status}: {constraint_name} (value={metric_value})")
        if not passed:
            failures.append({"constraint": constraint_name, "value": str(metric_value)})
            if fail_fast:
                raise ValueError(f"Constraint failed: {constraint_name}")

    all_passed = len(failures) == 0
    return all_passed, [{"name": r[0], "passed": r[1], "value": str(r[2])} for r in report]


# ── Drift detection ───────────────────────────────────────────────────────────

def detect_drift(
    reference_path: str = "profiles/reference.bin",
    current_path:   str = "profiles/current.bin",
    threshold:      float = 0.3,
) -> dict[str, Any]:
    """Compare two profiles and flag drifted columns."""
    from whylogs.core.utils.summary_drift_calculations import SummaryDriftAlgorithm

    ref  = DatasetProfileView.read(reference_path)
    curr = DatasetProfileView.read(current_path)

    drift_results: dict[str, float] = {}
    drifted_cols: list[str] = []

    ref_cols  = ref.to_pandas().index.tolist()
    curr_cols = curr.to_pandas().index.tolist()
    shared    = set(ref_cols) & set(curr_cols)

    for col in shared:
        try:
            col_ref  = ref.get_column(col)
            col_curr = curr.get_column(col)
            score    = SummaryDriftAlgorithm.compute(col_ref, col_curr)
            drift_results[col] = float(score) if score is not None else 0.0
            if drift_results[col] > threshold:
                drifted_cols.append(col)
        except Exception as e:
            drift_results[col] = 0.0

    drift_share = len(drifted_cols) / max(len(shared), 1)
    summary = {
        "drift_share": drift_share,
        "drifted_columns": drifted_cols,
        "column_scores": drift_results,
        "threshold": threshold,
        "alert": drift_share > 0.3,
    }

    print(f"\nDrift summary: {len(drifted_cols)}/{len(shared)} columns drifted "
          f"(share={drift_share:.2%})")
    for col in drifted_cols:
        print(f"  DRIFT: {col} (score={drift_results[col]:.4f})")

    return summary


# ── WhyLabs upload ────────────────────────────────────────────────────────────

def upload_to_whylabs(df: pd.DataFrame, api_key: str, org_id: str, dataset_id: str) -> None:
    """Profile and upload to WhyLabs for monitoring."""
    import os
    os.environ["WHYLABS_DEFAULT_DATASET_ID"] = dataset_id
    os.environ["WHYLABS_DEFAULT_ORG_ID"]     = org_id

    why.init(whylabs_api_key=api_key, default_dataset_id=dataset_id)
    result = why.log(df)
    result.writer("whylabs").write()
    print(f"Profile uploaded to WhyLabs: org={org_id}, dataset={dataset_id}")


# ── CI gate ───────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("--data",  required=True, help="CSV file to profile")
    parser.add_argument("--mode",  choices=["profile", "check", "drift"], default="check")
    parser.add_argument("--reference", help="Reference profile for drift check")
    args = parser.parse_args()

    df = pd.read_csv(args.data)

    if args.mode == "profile":
        profile_dataframe(df)
    elif args.mode == "check":
        passed, report = check_data_quality(df)
        print(f"\n{'All checks passed.' if passed else 'QUALITY CHECKS FAILED.'}")
        sys.exit(0 if passed else 1)
    elif args.mode == "drift":
        if not args.reference:
            print("--reference required for drift mode")
            sys.exit(1)
        # Save current profile first
        view = profile_dataframe(df, dataset_name="current")
        result = detect_drift(reference_path=args.reference)
        sys.exit(1 if result["alert"] else 0)

For the Evidently alternative when needing rich HTML reports, interactive dashboards, and a Testing Suite framework with pre-built test presets for data drift, data quality, and model performance that produce detailed pass/fail results with visual diffs — Evidently’s Report is more comprehensive for batch monitoring while whylogs is optimized for lightweight statistical sketches that work in streaming/real-time scenarios with minimal overhead, making it ideal for logging every row in a high-throughput inference pipeline. For the Great Expectations alternative when needing a Python-native assertion framework with detailed expectation suites, HTML validation reports, and deep integration with pandas/Spark/SQL — Great Expectations is richer for ETL validation while whylogs is purpose-built for ML data profiling with quantile sketches, cardinality estimation (HLL), and the WhyLabs platform for centralized monitoring dashboards. The Claude Skills 360 bundle includes whylogs skill sets covering DataFrame profiling, constraint sets, drift detection, segment profiling, and WhyLabs cloud upload. Start with the free tier to try ML data logging generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free