Polars中能否使用含3个及以上不同长度表达式的ufunc?
在Polars中使用3个及以上不同长度表达式的ufunc是否可行?
这是我之前提问的延续,但我认为它值得单独成题。请问在Polars中,是否可以使用带有3个及以上不同长度表达式的ufunc?
目前仅支持2个表达式的用法:
g(pl.col('x'), pl.col('y'))
对于3个及以上表达式,当前的临时解决方案是将这3列包装为struct,再用lambda映射,但该方案仅在x、y、z长度相同时可行,否则无法创建struct:
pl.struct('x', 'y', 'z').map(lambda t: g(t.struct['x'], t.struct['y'], t.struct['z']))
为便于说明,我用2个表达式复现了join_asof的功能,示例数据及代码如下:
示例数据
X: shape: (5, 1) ┌─────┐ │ x │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 3 │ │ 5 │ │ 7 │ │ 9 │ └─────┘ Y: shape: (3, 1) ┌─────┐ │ y │ │ --- │ │ i64 │ ╞═════╡ │ 2 │ │ 6 │ │ 10 │ └─────┘ 输出结果: shape: (5, 2) ┌─────┬───────────────┐ │ x ┆ x_join_asof_y │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═══════════════╡ │ 1 ┆ 2 │ │ 3 ┆ 6 │ │ 5 ┆ 6 │ │ 7 ┆ 10 │ │ 9 ┆ 10 │ └─────┴───────────────┘
实现代码
import numba as nb import polars as pl @nb.guvectorize([(nb.int64[:], nb.int64[:], nb.int64[:])], '(n),(m)->(n)', nopython=True) def join_asof(x, y, results): j = 0 for i in range(len(x)): while y[j] <= x[i]: j += 1 results[i] = y[j] xdf = pl.DataFrame({ 'x': [1, 3, 5, 7, 9] }) ydf = pl.DataFrame({ 'y': [2, 6, 10] }) ( xdf .lazy() .with_context( ydf .lazy() ) .with_columns( join_asof(pl.col('x'), pl.col('y')).alias('x_join_asof_y') ) .collect() )
内容的提问来源于stack exchange,提问作者T.H Rice
相关产品推荐
相关产品推荐

