如何使用Polars API对列表奇偶位置元素分别执行除法运算?
解决方案
可以通过Polars的向量化列表操作高效实现需求,无需逐元素遍历:
import polars as pl pl.Config(fmt_table_cell_list_len=8, fmt_str_lengths=100) data = { 'col': [[11, 21, 31, 41, 51], [12, 22, 32, 42, 52], [13, 23, 33, 43, 53]] } df = pl.DataFrame(data) # 执行列表元素转换 df = df.with_columns( pl.col("col").list.eval( pl.element() / pl.when(pl.int_range(0, pl.len()) % 2 == 0).then(5).otherwise(10) ).alias("col") ) print(df)
代码说明
pl.col("col"):选中需要处理的列表列list.eval(...):对每个列表内部的元素执行向量计算pl.int_range(0, pl.len()):生成当前列表的索引序列(0开始,对应元素的1-based位置为索引+1)pl.when(...).then(5).otherwise(10):根据索引判断除数:索引为偶数(对应1-based的第1、3、5…位)用5,索引为奇数(对应1-based的第2、4…位)用10pl.element() / ...:将列表中的每个元素除以对应位置的除数
执行后输出结果与预期一致:
shape: (3, 1) ┌────────────────────────────┐ │ col │ │ --- │ │ list[f64] │ ╞════════════════════════════╡ │ [2.2, 2.1, 6.2, 4.1, 10.2] │ │ [2.4, 2.2, 6.4, 4.2, 10.4] │ │ [2.6, 2.3, 6.6, 4.3, 10.6] │ └────────────────────────────┘
内容的提问来源于stack exchange,提问作者exch_cmmnt_memb
相关产品推荐
相关产品推荐

