Polars中pivot/unpivot如何保留原始struct数据类型(无需重解析)
解决Polars中Unpivot后Struct类型列转为字符串的恢复问题
当你在Polars中使用自定义plYearMonth struct类型的DataFrame执行pivot时,列名会被强制转换为字符串形式(struct会被序列化为类似{year:2023, month:12}的字符串);后续unpivot操作后,对应列自然会变成字符串类型。目前没有完全“无需解析”的直接恢复方法,但不需要手动创建字符串与struct的映射字典,可以利用Polars自身的struct解析能力快速转换:
方法1:使用pl.Struct.from_str()直接解析
如果plYearMonth是标准的struct类型(比如包含year和month字段),可以直接调用pl.Struct.from_str()将字符串解析回原struct类型,无需手动映射:
import polars as pl # 假设unpivot后的DataFrame名为df,date列是字符串类型 df = df.with_columns( pl.col("date").map_elements( lambda s: pl.Struct.from_str(s, dtype=pl.Struct([("year", pl.Int32), ("month", pl.Int32)])), return_dtype=pl.Struct([("year", pl.Int32), ("month", pl.Int32)]) ).alias("date") )
方法2:正则提取字段构造struct
如果追求更高性能(避免map_elements的逐行处理),可以用正则表达式提取字符串中的字段值,再重新构造struct:
df = df.with_columns( pl.struct( year=pl.col("date").str.extract(r'year:(\d+)', 1).cast(pl.Int32), month=pl.col("date").str.extract(r'month:(\d+)', 1).cast(pl.Int32) ).alias("date") )
特殊情况:自定义逻辑类型
如果plYearMonth是你自定义的逻辑类型(而非普通struct),你需要根据该类型的序列化规则,编写对应的解析函数,但依然不需要手动维护映射字典——只需根据字符串格式反推出原类型的字段值即可。
内容的提问来源于stack exchange,提问作者bzm3r
相关产品推荐
相关产品推荐

