Код: Выделить всё
import polars as pl
df_strs = pl.from_repr("""
┌───────────┬───────┐
│ Col_A ┆ Col_B │
│ --- ┆ --- │
│ str ┆ str │
╞═══════════╪═══════╡
│ AAABBCCCC ┆ AAB │
│ DDDEEFFFF ┆ DDE │
└───────────┴───────┘
""")
df_offsets = pl.from_repr("""
┌───────────────┬────────┬────────┬─────────┐
│ Reference_Col ┆ Offset ┆ Length ┆ Alias │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ str │
╞═══════════════╪════════╪════════╪═════════╡
│ Col_A ┆ 0 ┆ 3 ┆ Col_A_1 │
│ Col_A ┆ 3 ┆ 2 ┆ Col_A_2 │
│ Col_A ┆ 5 ┆ 4 ┆ Col_A_3 │
│ Col_B ┆ 0 ┆ 2 ┆ Col_B_1 │
│ Col_B ┆ 2 ┆ 1 ┆ Col_B_2 │
└───────────────┴────────┴────────┴─────────┘
""")
в приведенном выше примере результат будет следующим:
Код: Выделить всё
shape: (5, 4)
┌─────────┬─────────┬─────────┬─────────┬─────────┐
│ Col_A_1 ┆ Col_A_2 ┆ Col_A_3 ┆ Col_B_1 ┆ Col_B_2 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ str │
╞═════════╪═════════╪═════════╪═════════╪═════════╡
│ AAA ┆ BB ┆ CCCC ┆ AA ┆ B │
│ DDD ┆ EE ┆ FFFF ┆ DD ┆ E │
└─────────┴─────────┴─────────┴─────────┴─────────┘
Код: Выделить всё
df_offsets = df_offsets.transpose() # this converts our ints to strs
for s in df_offsets:
df_strs = df_strs.with_columns(
pl.col(s[0]).str.slice(int(s[1]), int(s[2])).alias(s[3])
)
Вывод:
Код: Выделить всё
>>>print(df_strs)
shape: (2, 7)
┌───────────┬───────┬─────────┬─────────┬─────────┬─────────┬─────────┐
│ Col_A ┆ Col_B ┆ Col_A_0 ┆ Col_A_1 ┆ Col_A_2 ┆ Col_B_0 ┆ Col_B_1 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ str ┆ str ┆ str │
╞═══════════╪═══════╪═════════╪═════════╪═════════╪═════════╪═════════╡
│ AAABBCCCC ┆ AAB ┆ AAA ┆ BB ┆ CCCC ┆ AA ┆ B │
│ DDDEEFFFF ┆ DDE ┆ DDD ┆ EE ┆ FFFF ┆ DD ┆ E │
└───────────┴───────┴─────────┴─────────┴─────────┴─────────┴─────────┘
Подробнее здесь: https://stackoverflow.com/questions/737 ... om-another
Мобильная версия