🐻

Polars Struct

に公開

struct

df = pl.DataFrame(
    {"person": [{"name": "Alice", "age": 32}, {"name": "Bob", "age": 41}]}
)
shape: (2, 1)
┌──────────────┐
│ person       │
│ ---          │
│ struct[2]    │
╞══════════════╡
│ {"Alice",32} │
│ {"Bob",41}   │
└──────────────┘

structの値を個別に取得する

structのfield nameを指定して取得すれば良い。

df.select([
    pl.col("person").struct.field("name"), 
    pl.col("person").struct.field("age"), 
])
shape: (2, 2)
┌───────┬─────┐
│ name  ┆ age │
│ ---   ┆ --- │
│ str   ┆ i64 │
╞═══════╪═════╡
│ Alice ┆ 32  │
│ Bob   ┆ 41  │
└───────┴─────┘

field nameが分からない場合はSeriesにしてからstruct.fieldsにアクセスすればfield nameが表示される。

df["person"].struct.fields
['name', 'age']

Discussion