Pandas DataFrame Groupby:如何计算满足条件的分组行数

时间:2020-04-23 01:30:10

标签: python pandas pandas-groupby

我想按“年龄”对行进行分组,并返回以下计数:1)每个组中有多少行,以及2)满足条件的行中有多少。

给出一个看起来像这样的DataFrame:

    Age     Died
0   26      0
1   26      0
2   27      1
3   28      0
4   28      1
5   28      1

我想返回一个看起来像这样的DataFrame:

   Age     Count    Died_Count
   26        2        0
   27        1        1
   28        3        2

我曾尝试使用各种聚合器(groupbysgroupby(['Age', 'Died'])等各种sum的各种组合,例如count,但似乎找不到成功的组合。有人可以指出我正确的方向吗?

2 个答案:

答案 0 :(得分:4)

您可以使用namedagg:

public static IntPtr FindDMAAddy(IntPtr hProc, IntPtr ptr, int[] offsets)
{
    var buffer = new byte[IntPtr.Size];
    foreach (int i in offsets)
    {
        ReadProcessMemory(hProc, ptr, buffer, buffer.Length, out var read);

        ptr = (IntPtr.Size == 4)
        ? IntPtr.Add(new IntPtr(BitConverter.ToInt32(buffer, 0)), i)
        : ptr = IntPtr.Add(new IntPtr(BitConverter.ToInt64(buffer, 0)), i);
    }
    return ptr;
}

var ammoAddr = FindDMAAddy(hProc, (IntPtr)(modBase + 0x10f4f4), new int[] { 0x374, 0x14, 0 });

答案 1 :(得分:2)

假设您的数据框为df

res=df.groupby("Age").agg({'Age': 'count', 'Died': 'sum'}).rename(columns={"Age":"Count"})

输出

        Count  Died
Age             
26       2     0
27       1     1
28       3     2

您可以重置索引并将“年龄”也设置为一列。

res = res.reset_index(drop=False)

输出

   Age  Count  Died
0   26      2     0
1   27      1     1
2   28      3     2
相关问题