Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 11 additions & 15 deletions pointblank/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -19689,11 +19689,7 @@ def interrogate(
# Capture original table dimensions before preprocessing
original_rows = get_row_count(data_tbl_step)
original_cols = get_column_count(data_tbl_step)
original_column_names = set(
data_tbl_step.columns
if hasattr(data_tbl_step, "columns")
else list(data_tbl_step.columns)
)
original_column_names = set(_get_column_names_safe(data_tbl_step))

# A function marked with `row_preserving()` is given the table with its row
# numbers, so that the rows it returns can be matched to the table's rows
Expand Down Expand Up @@ -19753,11 +19749,7 @@ def interrogate(
# Check if target column is synthetic (exists in processed but not original)
# Only check for single column names (not lists used in rows_distinct, etc.)
if column is not None and isinstance(column, str):
processed_column_names = set(
data_tbl_step.columns
if hasattr(data_tbl_step, "columns")
else list(data_tbl_step.columns)
)
processed_column_names = set(_get_column_names_safe(data_tbl_step))

# Check if the target column is in the processed table but not in original
if column in processed_column_names and column not in original_column_names:
Expand Down Expand Up @@ -29178,7 +29170,7 @@ def _seg_expr_from_string(data_tbl: Any, segments_expr: str) -> tuple[str, str]:
# values are tracked separately since Pandas represents them as `nan` or `pd.NA` rather than
# `None`, which can't be sorted alongside the other values and wouldn't match the `is_null()`
# filter used in `_apply_segments()`
if tbl_type in ["polars", "pandas", "pyspark"]:
if tbl_type in ["polars", "pandas", "pyspark", "pyarrow"]:
# Use Narwhals for supported DataFrame types
data_nw = nw.from_native(data_tbl)
unique_vals = data_nw.select(nw.col(segments_expr)).unique()
Expand Down Expand Up @@ -29271,8 +29263,8 @@ def _apply_segments(data_tbl: Any, segments_expr: tuple[str, str]) -> Any:
Parameters
----------
data_tbl
The data table to filter. It can be a Pandas DataFrame, Polars DataFrame, or an Ibis
backend table.
The data table to filter. It can be a Pandas, Polars, or PySpark DataFrame, a PyArrow
table, or an Ibis backend table.
segments_expr
The segments expression to apply. It is a tuple of the form `(column, value)`.

Expand All @@ -29287,8 +29279,8 @@ def _apply_segments(data_tbl: Any, segments_expr: tuple[str, str]) -> Any:
# Unpack the segments expression tuple for more convenient and explicit variable names
column, segment = segments_expr

if tbl_type in ["pandas", "polars", "pyspark"]:
# If the table is a Pandas, Polars, or PySpark DataFrame, transform to a Narwhals table
if tbl_type in ["pandas", "polars", "pyspark", "pyarrow"]:
# If the table is a Pandas, Polars, PySpark or PyArrow table, transform to a Narwhals table
# and perform the filtering operation

# Transform to Narwhals table if a DataFrame
Expand Down Expand Up @@ -29429,6 +29421,10 @@ def _apply_segments(data_tbl: Any, segments_expr: tuple[str, str]) -> Any:
else:
data_tbl = data_tbl.filter(data_tbl[column] == segment)

else:
# Returning the table unfiltered would check the step against every row without any error
raise ValueError(f"Unsupported table type: {tbl_type}")

return data_tbl


Expand Down
55 changes: 55 additions & 0 deletions tests/test_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class StrEnum(str, Enum):
import pandas as pd
import polars as pl
import pyarrow as pa
import pyarrow.compute as pc
from polars.testing import assert_frame_equal
import pytz
import ibis
Expand Down Expand Up @@ -169,6 +170,7 @@ class StrEnum(str, Enum):
_process_parquet_input,
_process_title_text,
_ValidationInfo,
_apply_segments,
_is_string_date,
_is_string_datetime,
_convert_string_to_date,
Expand Down Expand Up @@ -3602,6 +3604,59 @@ def add_computed_col(df):
assert len(validation.validation_info) == 2


def _segment_counts(validation: Validate) -> list[tuple[int, int, bool | None]]:
return [(i.n, i.n_passed, i.eval_error) for i in validation.validation_info]


@pytest.mark.parametrize("tbl_type", ["polars", "pandas", "pyarrow"])
def test_validation_segments_match_across_tables(tbl_type) -> None:
data = {"n": [1, 2, 3, 4, 5], "seg": ["a", "a", "b", "b", None]}
tbl = {
"polars": lambda: pl.DataFrame(data),
"pandas": lambda: pd.DataFrame(data),
"pyarrow": lambda: pa.table(data),
}[tbl_type]()

by_column = Validate(tbl).col_vals_gt(columns="n", value=2, segments="seg").interrogate()
assert _segment_counts(by_column) == [(2, 0, None), (2, 2, None), (1, 1, None)]

by_value = Validate(tbl).col_vals_gt(columns="n", value=2, segments=("seg", "b")).interrogate()
assert _segment_counts(by_value) == [(2, 2, None)]

by_group = (
Validate(tbl).col_vals_gt(columns="n", value=2, segments=("seg", ["a", "b"])).interrogate()
)
assert _segment_counts(by_group) == [(2, 0, None), (2, 2, None)]

by_missing = (
Validate(tbl).col_vals_gt(columns="n", value=2, segments=("seg", None)).interrogate()
)
assert _segment_counts(by_missing) == [(1, 1, None)]


def test_validation_pre_with_pyarrow_table() -> None:
tbl = pa.table({"n": [1, 2, 3, 4], "m": [10, 20, 30, 40]})

def add_column(t):
return t.append_column("computed", pc.multiply(t["n"], t["m"]))

validation = (
Validate(tbl).col_vals_gt(columns="computed", value=50, pre=add_column).interrogate()
)

step = validation.validation_info[0]
assert step.eval_error is None
assert (step.n, step.n_passed) == (4, 2)
assert "syn_target_col" in step.notes


def test_apply_segments_unsupported_table_type_raises(monkeypatch) -> None:
monkeypatch.setattr("pointblank.validate._get_tbl_type", lambda data: "unknown")

with pytest.raises(ValueError, match="Unsupported table type: unknown"):
_apply_segments(pl.DataFrame({"seg": ["a", "b"]}), ("seg", "a"))


@pytest.mark.skipif(not PYSPARK_AVAILABLE, reason="PySpark not available")
def test_validation_with_segments_and_pre_pyspark() -> None:
spark = get_spark_session()
Expand Down
Loading