请求实现基于现有DataFrame生成含决策比例的新DataFrame的代码
问题描述
现有一个长格式的DataFrame,结构如下:
| Product | Price | Decision | Sum |
|---|---|---|---|
| Food | 1 | yes | 39 |
| Food | 1 | no | 234 |
| Food | 2 | yes | 1312 |
| Food | 2 | no | 3123 |
| Clothes | 1 | yes | 323 |
| Clothes | 1 | no | 232 |
| Clothes | 3 | yes | 3 |
| Clothes | 3 | no | 434 |
需要创建新的DataFrame,按Product和Price分组,计算公式:(Decision为yes的Sum值) / (Decision为no的Sum值 + Decision为yes的Sum值)。比如Price为1的Food计算结果为39/(234+39)=0.1428571。最终新DataFrame结构如下:
| Product | Price | Decision |
|---|---|---|
| Food | 1 | 0.1428571 |
| Food | 2 | 0.295829 |
| Clothes | 1 | 0.581982 |
| Clothes | 3 | 0.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
相关产品推荐
相关产品推荐

