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

在Pandas中按组计算含BLOC模式与不含该模式行的最大值差值

解决方法

可以通过Pandas的分组(groupby)结合自定义计算逻辑实现需求,具体步骤如下:

1. 构造示例DataFrame

先还原你的输入数据:

import pandas as pd

df = pd.DataFrame({
    'Groups': ['G1', 'G1', 'G1', 'G1', 'G1', 'G2', 'G2', 'G2', 'G2', 'G3', 'G3', 'G3'],
    'Name': ['BLOC_Homo_sapiens', 'BLOC_Chimpenzee', 'BLOC_Bonobo', 'Canis_lupus', 'Danio_rerio',
             'BLOC_Homo_sapiens', 'BLOC_Bonobo', 'Mus_musculus', 'Cules_pupiens',
             'BLOC_Gorrilla', 'Cimex_lectularius', 'Bombus_terrestris'],
    'Value': [100, 99, 80, 20, 10, 30, 29, 28, 26, 300, 10, 9]
})

2. 计算diff_length列

使用groupby按Groups分组,通过transform方法将每组的计算结果广播到组内所有行:

def calculate_diff(group):
    # 提取组内Name含BLOC的行,取Value最大值
    max_bloc = group[group['Name'].str.contains('BLOC')]['Value'].max()
    # 提取组内Name不含BLOC的行,取Value最大值
    max_non_bloc = group[~group['Name'].str.contains('BLOC')]['Value'].max()
    return max_bloc - max_non_bloc

# 添加diff_length列
df['diff_length'] = df.groupby('Groups').transform(calculate_diff)

3. 查看结果

执行后得到的DataFrame即为目标结果:

Groups               Name  Value  diff_length
0      G1  BLOC_Homo_sapiens    100           80
1      G1    BLOC_Chimpenzee     99           80
2      G1        BLOC_Bonobo     80           80
3      G1        Canis_lupus     20           80
4      G1        Danio_rerio     10           80
5      G2  BLOC_Homo_sapiens     30            2
6      G2        BLOC_Bonobo     29            2
7      G2       Mus_musculus     28            2
8      G2      Cules_pupiens     26            2
9      G3     BLOC_Gorrilla    300          290
10     G3  Cimex_lectularius     10          290
11     G3  Bombus_terrestris      9          290

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:55:20