I was able to get this to work but is seems a little clunky and not as elegant as I was hoping for.
df3 = (pl.DataFrame(data)
.with_columns(
diff = pl.col('strike') - pl.col('target'))
.with_columns(
max_lt_zero = pl.when(pl.col('diff') < 0).then(pl.col('diff')).otherwise(None).max(),
min_gt_zero = pl.when(pl.col('diff') > 0).then(pl.col('diff')).otherwise(None).min())
.filter(
pl.max_horizontal (
pl.col('diff') == pl.col('max_lt_zero'),
pl.col('diff') == pl.col('min_gt_zero')))
.select(['strike', 'target', 'diff'])
)
shape: (2, 3)
┌────────┬────────┬──────┐
│ strike ┆ target ┆ diff │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞════════╪════════╪══════╡
│ 15 ┆ 16 ┆ -1 │
│ 20 ┆ 16 ┆ 4 │
└────────┴────────┴──────┘