我得到了一个带有json字符串表示的数据帧:
df = pl.DataFrame({
"json": [
'{"x":[0,1,2,3], "y":[10,20,30,40]}',
'{"x":[0,1,2,3], "y":[10,20,30,40]}',
'{"x":[0,1,2,3], "y":[10,20,30,40]}'
]
})
shape: (3, 1)
┌───────────────────────────────────┐
│ json │
│ --- │
│ str │
╞═══════════════════════════════════╡
│ {"x":[0,1,2,3], "y":[10,20,30,40… │
│ {"x":[0,1,2,3], "y":[10,20,30,40… │
│ {"x":[0,1,2,3], "y":[10,20,30,40… │
└───────────────────────────────────┘
现在我要计算y的average,其中x > 0和x < 3分别为每行.
这是我目前的工作解决方案:
首先计算字符串->;dict,然后创建一个按x过滤的数据帧.
df = df.with_columns([
pl.col('json').apply(lambda x: pl.DataFrame(ast.literal_eval(x)).filter((pl.col('x') < 3) & (pl.col('x') > 0))['y'].mean())
])
shape: (3, 1)
┌──────┐
│ json │
│ --- │
│ f64 │
╞══════╡
│ 25.0 │
│ 25.0 │
│ 25.0 │
└──────┘
这可以很好地工作,但对于大型数据集,Apply函数会显著减慢这一过程.
有没有更优雅、更快捷的方法呢?