Python 极坐标 - 如何聚合数据帧

问题描述 投票:0回答:1

目标

在 Python 中有效聚合 Polars 数据框中函数返回的数据帧。

环境

  • Windows 10
  • Python 3.9.18
  • 极地 0.20.18

到目前为止我做了什么

我想要此代码的等效内容(这是一个虚拟代码)。

def dummy_dataframe(val):
    return pl.DataFrame(
        {
            "x": [va1 + 1, 0, 1],
            "y": [val + 2, 8, 9],
            "z": [val + 3, 5, 6],
        }
    )

df = pl.DataFrame(
    {
        "a": ["a", "b", "a", "b"],
    }
)

groups = df.groupby('a').agg(pl.apply(exprs=['a'], function=lambda x: dummy_dataframe(x)).alias('result'))
results = []
for row in groups.iter_rows():
    group_name = row[0]
    group_val = row[1]
    df_ret = group_val.with_columns(pl.lit(group_name).alias('group_name'))
    results.append(df_ret)
df_results = pl.concat(results)
df_results

但是,我认为

iter_rows()
效率很低。 这个极坐标文档说“行迭代不是最佳的,因为基础数据以柱状形式存储;在可能的情况下。”由于
iter_rows()
在 Pandas 中效率不是很高,我可以想象它在 Polars 中也是一样的。

研究

谷歌搜索“单元格中的极坐标数据帧”和“极坐标聚合数据帧”并检查每个的前 10 页并没有给我太多信息。

结论

如何有效聚合函数返回的数据帧?

python windows dataframe group-by python-polars
1个回答
0
投票

遍历行可能效率很低。我建议在这种情况下使用

grouby
apply

import polars as pl

def dummy_dataframe(val):
    return pl.DataFrame({
        "x": [val + 1, 0, 1],
        "y": [val + 2, 8, 9],
        "z": [val + 3, 5, 6],
    })

df = pl.DataFrame({"a": ["a", "b", "a", "b"]})

def process_group(df):
 
    group_name = df['a'][0]
    val = ord(group_name) - ord('a')
    result_df = dummy_dataframe(val)
    return result_df.with_columns(pl.lit(group_name).alias('group_name'))

df_results = df.group_by("a", maintain_order=True).apply(process_group)

print(df_results)

这会导致

shape: (6, 4)
┌─────┬─────┬─────┬────────────┐
│ x   ┆ y   ┆ z   ┆ group_name │
│ --- ┆ --- ┆ --- ┆ ---        │
│ i64 ┆ i64 ┆ i64 ┆ str        │
╞═════╪═════╪═════╪════════════╡
│ 1   ┆ 2   ┆ 3   ┆ a          │
│ 0   ┆ 8   ┆ 5   ┆ a          │
│ 1   ┆ 9   ┆ 6   ┆ a          │
│ 2   ┆ 3   ┆ 4   ┆ b          │
│ 0   ┆ 8   ┆ 5   ┆ b          │
│ 1   ┆ 9   ┆ 6   ┆ b          │
└─────┴─────┴─────┴────────────┘
© www.soinside.com 2019 - 2024. All rights reserved.