Polars.DataFrame.unpivot()无法使用pl.exclude()作为index参数的问题咨询
在Polars的
unpivot方法中使用列选择器的解决方案 问题分析
尽管pl.DataFrame.unpivot的类型提示标注index参数支持ColumnNameOrSelector类型,但实际使用时直接传入pl.exclude()这类表达式选择器会触发类型错误——因为该参数目前仅接受列名字符串或字符串列表,类型提示存在描述偏差。
解决方法
先通过选择器获取目标列的名称列表,再将列表传入index参数:
import polars as pl df = pl.DataFrame({ 'foo' : ['one', 'two', 'three'], 'bar' : ['four', 'five', 'six'], 'baz' : [10, 20, 30], 'qux' : [50, 60, 70] }) column_list = ['baz', 'qux'] # 先通过选择器提取目标列名列表 index_cols = df.select(pl.exclude(column_list)).columns # 将列名列表传入unpivot的index参数 result = df.unpivot(column_list, index=index_cols) print(result)
输出结果
shape: (6, 3) ┌───────┬──────┬──────┐ │ foo ┆ bar ┆ value│ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 │ ├───────┼──────┼──────┤ │ one ┆ four ┆ 10 │ │ two ┆ five ┆ 20 │ │ three ┆ six ┆ 30 │ │ one ┆ four ┆ 50 │ │ two ┆ five ┆ 60 │ │ three ┆ six ┆ 70 │ └───────┴──────┴──────┘
补充说明
如果需要使用其他列选择器(如pl.selectors.numeric()、pl.selectors.string()),同样可以通过df.select(selector).columns的方式提取列名列表,再传入unpivot的index或其他相关参数。
内容的提问来源于stack exchange,提问作者Kazdegotepu
相关产品推荐
相关产品推荐

