将包含字典条目的 Polars 列分解为子列

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

我有以下格式的 Polars 数据框。

enter image description here

我想分解 Price 和 Duration 列,以便 idxmaxmax 成为子列。

enter image description here

我必须对数据框或列执行哪组方法链接才能实现此类转换?是否可以将字典扩展为子列?如果链接太复杂,将 Polars 数据帧转换为 Pandas 数据帧,然后展开每个字典行会更简单吗?

python-polars
1个回答
2
投票

假设您的“dict”列是

pl.Struct
dtypes(我相信极坐标会在大多数
df
创作上自动转换,如果不尝试
cast
?),您可以
unnest
这些列。

df = pl.DataFrame({'location' : ['new york'], 'price' : [{'idxmax' : [3, 4, 1], 'max' : 32.43}]})
shape: (1, 2)
┌──────────┬───────────────────┐
│ location ┆ price             │
│ ---      ┆ ---               │
│ str      ┆ struct[2]         │
╞══════════╪═══════════════════╡
│ new york ┆ {[3, 4, 1],32.43} │
└──────────┴───────────────────┘
df.unnest('price')
shape: (1, 3)
┌──────────┬───────────┬───────┐
│ location ┆ idxmax    ┆ max   │
│ ---      ┆ ---       ┆ ---   │
│ str      ┆ list[i64] ┆ f64   │
╞══════════╪═══════════╪═══════╡
│ new york ┆ [3, 4, 1] ┆ 32.43 │
└──────────┴───────────┴───────┘

编辑:我明白你所说的“子列”的意思,其中“价格”然后是“idxmax”等,据我所知,这是不可能的,但如果你确实需要,你可以随时将新列重命名为“price_idxmax”或其他名称以某种方式保存下来的。另一种选择是保留

struct
列并引用“子列”,如下所示:

pl.col('price').struct.field('idxmax')

© www.soinside.com 2019 - 2024. All rights reserved.