摘要行或数据框

时间:2016-12-18 08:06:59

标签: python pandas

我想在下表中有一个摘要行。结果将是会员ID,收据总和和支出总和的唯一计数。但我能想到的唯一方法是创建一个具有相同值的新列,并使用相同的值列来执行groupby聚合函数来获取结果。有更简单的方法吗?

import pandas as pd
df=pd.DataFrame({'Mbr ID':['ID0001','ID0002','ID0003','ID0004'],
                 'Receipts':[3,5,12,5],                 
                 'Spending':[130,22,313,46],
                 })

enter image description here

2 个答案:

答案 0 :(得分:2)

您需要按Mbr ID列和locReceiptsSpending df.loc['Summary'] = [df['Mbr ID'].nunique(), df.Receipts.sum(), df.Spending.sum()] print (df) Mbr ID Receipts Spending 0 ID0001 3 130 1 ID0002 5 22 2 ID0003 12 313 3 ID0004 5 46 Summary 4 25 511 添加新的摘要行:

index

如果需要df.loc[df.index[-1] + 1] = [df['Mbr ID'].nunique(), df.Receipts.sum(), df.Spending.sum()] print (df) Mbr ID Receipts Spending 0 ID0001 3 130 1 ID0002 5 22 2 ID0003 12 313 3 ID0004 5 46 4 4 25 511 的新行与前一行相同,则增加1:

public partial class TransparentTextBox : TextBox
    {
        public TransparentTextBox()
        {
            InitializeComponent();

            SetStyle(ControlStyles.SupportsTransparentBackColor |
             ControlStyles.OptimizedDoubleBuffer |
             ControlStyles.AllPaintingInWmPaint |
             ControlStyles.ResizeRedraw |
             ControlStyles.UserPaint, true);

            BackColor = Color.FromArgb(70, Color.Black);
        }
    }

答案 1 :(得分:0)

就这样做。

df.groupby('Mbr ID').agg({
        'Mbr ID': 'count', 
        'Receipts': 'sum', 
        'Spending': 'sum'})

#         Mbr ID  Spending  Receipts
# Mbr ID                            
# ID0001       1       130         3
# ID0002       1        22         5
# ID0003       1       313        12
# ID0004       1        46         5