79231680

Date: 2024-11-27 19:43:59
Score: 0.5
Natty:
Report link

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    │
└────────┴────────┴──────┘


Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: nybhh