You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过OML4Py的oml.group_apply实现双列分组查询?

用OML4Py的oml.group_apply实现多列分组操作

要实现你给出的SQL多列分组统计逻辑,只需通过自定义分组处理函数结合oml.group_apply即可完成,具体步骤如下:

1. 编写分组统计的自定义函数

首先定义一个Python函数,接收每个分组的Pandas DataFrame,计算需要的统计值并返回结果:

import pandas as pd

def calculate_group_stats(group_df):
    # 提取当前分组的mgr和deptno值(每组内分组键值一致,取第一个即可)
    mgr = group_df['mgr'].iloc[0]
    deptno = group_df['deptno'].iloc[0]
    # 计算统计量
    count_mgr = group_df['mgr'].count()
    count_deptno = group_df['deptno'].count()
    # 返回包含分组键和统计值的DataFrame
    return pd.DataFrame({
        'mgr': [mgr],
        'count(mgr)': [count_mgr],
        'count(deptno)': [count_deptno],
        'deptno': [deptno]
    })

2. 调用oml.group_apply执行分组操作

加载数据库中的emp表为OML DataFrame,指定分组列并传入自定义函数:

import oml

# 同步数据库中的emp表为OML DataFrame
emp_oml = oml.sync(table='emp')

# 执行多列分组统计
result_oml = emp_oml.group_apply(
    group_cols=['mgr', 'deptno'],  # 指定两列作为分组键
    func=calculate_group_stats,
    return_type='pandas'  # 直接返回Pandas DataFrame,也可选'oml'保留数据库连接
)

# 按deptno排序并输出结果
final_result = result_oml.sort_values('deptno').reset_index(drop=True)
print(final_result)

预期输出

执行后会得到与你给出的SQL结果一致的输出:

mgr  count(mgr)  count(deptno)  deptno
0  7782           1              1      10
1  7839           1              1      10
2     0           1              1      10
3  7566           2              2      20
4  7788           1              1      20
5  7839           1              1      20
6  7902           1              1      20
7  7698           5              5      30
8  7839           1              1      30

注意事项

  • 自定义函数的输入是单个分组的Pandas DataFrame,分组列的取值在每组内是唯一的,因此可以用iloc[0]提取分组键值
  • 如果需要将结果保留在数据库中,可将return_type设为'oml',后续可直接对result_oml执行数据库操作
  • 排序也可在OML层面完成:result_oml.order_by('deptno')

内容的提问来源于stack exchange,提问作者Philip Cannata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 19:47:27