pandas 根据行条件进行分组

Jes*_*ica 2 python pandas

我有一个样本数据集:

import pandas as pd


d = {

 'H#': ['12843','12843','12843','12843','20000','20000','20000','20000','20000'],
 'measure':[1,1,1,3,3,3,3,2,2],
 'D':[1,0,2,1,1,1,2,1,1],
 'N':[2,3,1,4,5,0,0,0,2]
}
df = pd.DataFrame(d)
df = df.reindex_axis(['H#','measure', 'D','N'], axis=1) 
Run Code Online (Sandbox Code Playgroud)

看起来像:

    H#      measure  D  N
0  12843        1    1  2
1  12843        1    0  3
2  12843        1    2  1
3  12843        3    1  4
4  20000        3    1  5
5  20000        3    1  0
6  20000        3    2  0
7  20000        2    1  0
8  20000        2    1  2
Run Code Online (Sandbox Code Playgroud)

我想将 groupby 应用于不是通过 'H#' 和 'measure'测量=3 的行,以求和 'D' 和 'N'。期望的输出:

    H#      measure  D  N
0  12843        1    3  6
3  12843        3    1  4
4  20000        3    1  5
5  20000        3    1  0
6  20000        3    2  0
7  20000        2    2  2
Run Code Online (Sandbox Code Playgroud)

我的尝试:

mask=df["measure"]!=3  #first to mask the rows for the groupby

#the following line has the wrong syntax, how can i apply groupby to the masked dataset?
df.loc[mask,]= df.loc[mask,].groupby(['H#','measure'],as_index=False)['D','N'].sum()  
Run Code Online (Sandbox Code Playgroud)

最后一行代码的语法是错误的,我如何将 groupby 应用于屏蔽数据集?

Max*_*axU 5

国际大学学院:

In [90]: (df[df.measure!=3]
            .groupby(['H#','measure'], as_index=False)
            .sum()
            .append(df.loc[df.measure==3]))
Out[90]:
      H#  measure  D  N
0  12843        1  3  6
1  20000        2  2  2
3  12843        3  1  4
4  20000        3  1  5
5  20000        3  1  0
6  20000        3  2  0
Run Code Online (Sandbox Code Playgroud)