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

如何在Pandas DataFrame中计算分组行的占比?

解决Pandas DataFrame的百分比计算问题

Hey there! Let's tackle this problem step by step. What you need is to calculate the percentage each absolute Amount contributes to its Name group's total absolute amount. Here's the most straightforward and efficient approach using Pandas:

Core Logic Breakdown

  1. Group by Name to get group-level totals: We use transform() instead of a regular sum() because transform() preserves the original DataFrame's row count—this lets every row access its own group's total absolute amount.
  2. Compute the percentage column: For each row, divide the absolute value of Amount by its group's total absolute amount, multiply by 100, and round to two decimal places to match your expected format.

Full Code Example

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'Name': ['ABC', 'ABC', 'XYZ', 'XYZ'],
    'Category': ['Science', 'History', 'Science', 'Geography'],
    'Amount': [50, -100, 600, -300]
})

# 计算每个Name组的总绝对值(保留原行结构)
total_abs_per_group = df.groupby('Name')['Amount'].transform(lambda x: x.abs().sum())

# 添加Category%列,保留两位小数
df['Category%'] = (df['Amount'].abs() / total_abs_per_group * 100).round(2)

# 如果你需要把XYZ的Amount改成示例中的500/-500,执行下面这行:
# df.loc[df['Name'] == 'XYZ', 'Amount'] = [500, -500]

print(df)

Result Explanation

  • For the ABC group: Total absolute amount is 50 + 100 = 150. So 50/150 ≈ 33.33% and 100/150 ≈ 66.67%, which matches your expected output.
  • If you adjust XYZ's Amount to 500 and -500, the total absolute amount becomes 1000, so both rows will show 50.00% for Category%.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:51:13