如何在Polars的DataFrame.map_rows中传递命名行(字典形式)给自定义函数?
如何在Polars的DataFrame.map_rows中传递命名行(字典形式)给自定义函数?
我最近在使用Polars的pl.DataFrame.map_rows方法时遇到了个困扰:我想让自定义函数接收字典形式的行数据,而不是默认的元组,但尝试了下面的写法后出问题了:
df.map_rows(lambda x: udf({k:v for k, v in zip(df.columns, x)}))
运行这段代码直接抛出了RuntimeError: Already mutably borrowed错误。
我去翻了官方文档,里面提到:
The frame-level map_rows cannot track column names (as the UDF is a black-box that may arbitrarily drop, rearrange, transform, or add new columns); if you want to apply a UDF such that column names are preserved, you should use the expression-level map_elements syntax instead.
但我还是有点疑惑:就算map_rows无法追踪列名变化,为什么不能像df.row(i, named=True)那样,把每行数据包装成带键名的字典传给自定义函数呢?明明结构体是可以支持命名的啊。
我知道目前可以通过遍历df.rows()来处理每行数据,之后再转回pl.DataFrame,但我更希望能在Polars的API体系内完成这个操作,不想跳出框架去做额外的转换。
备注:内容来源于stack exchange,提问作者paulduf
相关产品推荐
相关产品推荐

