如何在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
- Group by
Nameto get group-level totals: We usetransform()instead of a regularsum()becausetransform()preserves the original DataFrame's row count—this lets every row access its own group's total absolute amount. - Compute the percentage column: For each row, divide the absolute value of
Amountby 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
ABCgroup: Total absolute amount is50 + 100 = 150. So50/150 ≈ 33.33%and100/150 ≈ 66.67%, which matches your expected output. - If you adjust XYZ's
Amountto 500 and -500, the total absolute amount becomes1000, so both rows will show50.00%forCategory%.
内容的提问来源于stack exchange,提问作者asimo
相关产品推荐
相关产品推荐

