我可以想到两种可能的方法来做到这一点.
Regex提取物
df.with_columns(pl.col('sector_exposure').str.extract(x+r"=(\d+\.\d+)").cast(pl.Float64).alias(x)
for x in ["Technology", "Financials", "Health Care", "Consumer Discretionary",
"Consumer Staples","Industrials"])
shape: (2, 7)
┌────────────────┬────────────┬────────────┬─────────────┬────────────────┬──────────┬─────────────┐
│ sector_exposur ┆ Technology ┆ Financials ┆ Health Care ┆ Consumer ┆ Consumer ┆ Industrials │
│ e ┆ --- ┆ --- ┆ --- ┆ Discretionary ┆ Staples ┆ --- │
│ --- ┆ f64 ┆ f64 ┆ f64 ┆ --- ┆ --- ┆ f64 │
│ str ┆ ┆ ┆ ┆ f64 ┆ f64 ┆ │
╞════════════════╪════════════╪════════════╪═════════════╪════════════════╪══════════╪═════════════╡
│ Technology=0.2 ┆ 0.207 ┆ 0.09 ┆ 0.084 ┆ 0.069 ┆ null ┆ null │
│ 07;Financials= ┆ ┆ ┆ ┆ ┆ ┆ │
│ 0.090;Health ┆ ┆ ┆ ┆ ┆ ┆ │
│ Care=0.084;Con ┆ ┆ ┆ ┆ ┆ ┆ │
│ sumer Discreti ┆ ┆ ┆ ┆ ┆ ┆ │
│ onary=0.069 ┆ ┆ ┆ ┆ ┆ ┆ │
│ Financials=0.2 ┆ null ┆ 0.25 ┆ 0.2 ┆ null ┆ 0.15 ┆ 0.4 │
│ 50;Health Care ┆ ┆ ┆ ┆ ┆ ┆ │
│ =0.200;Consume ┆ ┆ ┆ ┆ ┆ ┆ │
│ r Staples=0.15 ┆ ┆ ┆ ┆ ┆ ┆ │
│ 0;Industrials= ┆ ┆ ┆ ┆ ┆ ┆ │
│ 0.400 ┆ ┆ ┆ ┆ ┆ ┆ │
└────────────────┴────────────┴────────────┴─────────────┴────────────────┴──────────┴─────────────┘
在这一个,我们指望所有的数字是十进制(你可以调整regex,以绕过这一位)和所有扇区被预先指定的发生器在with_columns
内,
拆分和枢轴
(
df
.with_columns(str_split=pl.col('sector_exposure').str.split(';'))
.explode('str_split')
.with_columns(
pl.col('str_split')
.str.split('=')
.list.to_struct(fields=['sector','value'])
)
.unnest('str_split')
.pivot(values='value',index='sector_exposure',columns='sector',aggregate_function='first')
.with_columns(pl.exclude('sector_exposure').cast(pl.Float64))
)
shape: (2, 7)
┌────────────────┬────────────┬────────────┬─────────────┬────────────────┬──────────┬─────────────┐
│ sector_exposur ┆ Technology ┆ Financials ┆ Health Care ┆ Consumer ┆ Consumer ┆ Industrials │
│ e ┆ --- ┆ --- ┆ --- ┆ Discretionary ┆ Staples ┆ --- │
│ --- ┆ f64 ┆ f64 ┆ f64 ┆ --- ┆ --- ┆ f64 │
│ str ┆ ┆ ┆ ┆ f64 ┆ f64 ┆ │
╞════════════════╪════════════╪════════════╪═════════════╪════════════════╪══════════╪═════════════╡
│ Technology=0.2 ┆ 0.207 ┆ 0.09 ┆ 0.084 ┆ 0.069 ┆ null ┆ null │
│ 07;Financials= ┆ ┆ ┆ ┆ ┆ ┆ │
│ 0.090;Health ┆ ┆ ┆ ┆ ┆ ┆ │
│ Care=0.084;Con ┆ ┆ ┆ ┆ ┆ ┆ │
│ sumer Discreti ┆ ┆ ┆ ┆ ┆ ┆ │
│ onary=0.069 ┆ ┆ ┆ ┆ ┆ ┆ │
│ Financials=0.2 ┆ null ┆ 0.25 ┆ 0.2 ┆ null ┆ 0.15 ┆ 0.4 │
│ 50;Health Care ┆ ┆ ┆ ┆ ┆ ┆ │
│ =0.200;Consume ┆ ┆ ┆ ┆ ┆ ┆ │
│ r Staples=0.15 ┆ ┆ ┆ ┆ ┆ ┆ │
│ 0;Industrials= ┆ ┆ ┆ ┆ ┆ ┆ │
│ 0.400 ┆ ┆ ┆ ┆ ┆ ┆ │
└────────────────┴────────────┴────────────┴─────────────┴────────────────┴──────────┴─────────────┘
在这一个你做了一个"回合"分裂在分号,然后爆炸.然后,你又在平等上分裂,但你把它变成一个 struct ,然后拆除.从那里你将扇区向上旋转到列.
如果扇区以相同的顺序存在,那么你可以使用str.extract_groups
个,但不同的顺序,我不认为它工作.