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

请求实现基于现有DataFrame生成含决策比例的新DataFrame的代码

问题描述

现有一个长格式的DataFrame,结构如下:

ProductPriceDecisionSum
Food1yes39
Food1no234
Food2yes1312
Food2no3123
Clothes1yes323
Clothes1no232
Clothes3yes3
Clothes3no434

需要创建新的DataFrame,按Product和Price分组,计算公式:(Decision为yes的Sum值) / (Decision为no的Sum值 + Decision为yes的Sum值)。比如Price为1的Food计算结果为39/(234+39)=0.1428571。最终新DataFrame结构如下:

ProductPriceDecision
Food10.1428571
Food20.295829
Clothes10.581982
Clothes30.006865

实际数据集包含6种Product,Price范围0-99。

解决方案

以下是两种基于Pandas的实现方案,适配你的需求:

方法一:用pivot_table转换格式后计算

import pandas as pd

# 构建示例数据(实际使用时替换为你的数据集)
data = {
    'Product': ['Food', 'Food', 'Food', 'Food', 'Clothes', 'Clothes', 'Clothes', 'Clothes'],
    'Price': [1, 1, 2, 2, 1, 1, 3, 3],
    'Decision': ['yes', 'no', 'yes', 'no', 'yes', 'no', 'yes', 'no'],
    'Sum': [39, 234, 1312, 3123, 323, 232, 3, 434]
}
df = pd.DataFrame(data)

# 将长表转宽表,按Product和Price分组,yes/no作为列
pivot_df = df.pivot_table(index=['Product', 'Price'], columns='Decision', values='Sum', aggfunc='sum')

# 计算目标比例
pivot_df['Decision'] = pivot_df['yes'] / (pivot_df['yes'] + pivot_df['no'])

# 重置索引并保留需要的列
result_df = pivot_df.reset_index()[['Product', 'Price', 'Decision']]

print(result_df)

方法二:用groupby+自定义聚合函数

import pandas as pd

# 构建示例数据(实际使用时替换为你的数据集)
data = {
    'Product': ['Food', 'Food', 'Food', 'Food', 'Clothes', 'Clothes', 'Clothes', 'Clothes'],
    'Price': [1, 1, 2, 2, 1, 1, 3, 3],
    'Decision': ['yes', 'no', 'yes', 'no', 'yes', 'no', 'yes', 'no'],
    'Sum': [39, 234, 1312, 3123, 323, 232, 3, 434]
}
df = pd.DataFrame(data)

# 自定义聚合函数:计算当前分组中yes的Sum占总Sum的比例
def calculate_ratio(group):
    yes_sum = group[group['Decision'] == 'yes']['Sum'].sum()
    total_sum = group['Sum'].sum()
    return yes_sum / total_sum

# 按Product和Price分组,应用聚合函数
result_df = df.groupby(['Product', 'Price']).apply(calculate_ratio).reset_index(name='Decision')

print(result_df)

两种方案都能输出符合要求的结果:方法一适合每个分组都包含yes和no的场景;方法二更灵活,若部分分组缺失yes/no值,会返回NaN(可根据需求添加默认值处理)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:35:33