在 Python Polars 中捕获 f 字符串中的组

问题描述 投票:0回答:1

我正在尝试转换这样的系列

s = pl.Series(['{1-5}', '1'])

这样的系列

pl.Series(['{1, 2, 3, 4, 5}', '1'])

如果我手动编写与第一个元素的极值相对应的

1
5
,即

,我可以做到这一点
s.str.replace(r'\{(\d+)-(\d+)\}', f'{set(range(1, 6))}')

但我想引用捕获组,例如类似的东西

s.str.replace(r'\{(\d+)-(\d+)\}', f'{set(range(int('${1}'), int('${2}' + 1)))}')

我该怎么做?

regex python-polars
1个回答
0
投票

您不能使用回调

.str.replace

您可以提取您想要的部分并在 Polars 表达式中使用它们:

digits = pl.all().str.extract_all(r"\d+").cast(pl.List(pl.Int64))

expanded_range =  (
   pl.int_ranges(digits.list.first(), digits.list.last() + 1)
     .cast(pl.List(pl.String))
     .list.join(", ")
)

s.to_frame().with_columns(
   pl.when(digits.list.len() > 1)
     .then(pl.format("{{}}", expanded_range))
     .otherwise(pl.all())
     .alias("result")
)
shape: (2, 2)
┌───────┬─────────────────┐
│       ┆ result          │
│ ---   ┆ ---             │
│ str   ┆ str             │
╞═══════╪═════════════════╡
│ {1-5} ┆ {1, 2, 3, 4, 5} │
│ 1     ┆ 1               │
└───────┴─────────────────┘
© www.soinside.com 2019 - 2024. All rights reserved.