并行查询polar数据框中过滤器表达式列表的索引



我想获得的索引列表的过滤器的极性,并从中得到一个稀疏矩阵,我怎么能并行的过程?这就是我现在所拥有的,一种非常幼稚和蛮力的方式来实现我所需要的,但这有一些严重的性能问题

def get_sparse_matrix(exprs: list[pl.Expr]) -> scipy.sparse.csc_matrix:
df = df.with_row_count('_index')
rows: list[int] = []
cols: list[int] = []
for col, expr in enumerate(exprs):
r = self.df.filter(expr)['_index']
rows.extend(r)
cols.extend([col] * len(r))
X = csc_matrix((np.ones(len(rows)), (rows, cols)), shape= 
(len(self.df), len(rules)))
return X

示例输入:

# df is a polars dataframe with size 8 * 3
df = pl.DataFrame(
[[1,2,3,4,5,6,7,8], 
[3,4,5,6,7,8,9,10], 
[5,6,7,8,9,10,11,12],
[5,6,41,8,21,10,51,12],
])
# three polars expressions
exprs = [pl.col('column_0') > 3, pl.col('column_1') < 6, pl.col('column_4') > 11]

示例输出:X是大小为8 (number of records) X 3 (number of expressions)的稀疏矩阵,如果i条记录匹配j条表达式

,则i,j处的元素等于1

所以我不完全确定你到底想要什么,但我希望满足你的需求

import polars as pl
from scipy.sparse import csc_matrix
import numpy as np
df = pl.DataFrame(
[[1,2,3,4,5,6,7,8], 
[3,4,5,6,7,8,9,10], 
[5,6,7,8,9,10,11,12],
[5,6,41,8,21,10,51,12],
])

exprs = [(pl.col('column_0') > 3).cast(pl.Int8), 
(pl.col('column_1') < 6).cast(pl.Int8), 
(pl.col('column_3') > 11).cast(pl.Int8)]
X = df.select(exprs)
csc_matrix(X.to_numpy())

GroupBy对象是从键到索引列表的映射,并且在极值中实现得非常快。你可以这样做:

(df
.with_column((pl.col('column_0') > 3).alias('e1'))
.groupby('e1')
._groups()
.filter(pl.col("e1"))
)[0,1]

请参阅我最近的博客文章,了解更多细节:https://braaannigan.github.io/software/2022/10/11/polars-index.html

最新更新