pandas groupby在行条件下

时间:2017-12-18 22:40:50

标签: 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) 

看起来像:

    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

我想将groupby应用于 not measure = 3 的行'H#'和'measure'来汇总'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

我的尝试:

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()  

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

2 个答案:

答案 0 :(得分:3)

IIUC:

align-content: flex-start

答案 1 :(得分:2)

你可以使用分解你的df和group然后连接回来:

pd.concat([df.query('measure == 3'),
           df.query('measure != 3')
             .groupby(['H#','measure'],as_index=False)['D','N']
             .agg('sum')])

输出:

      H#  measure  D  N
3  12843        3  1  4
4  20000        3  1  5
5  20000        3  1  0
6  20000        3  2  0
0  12843        1  3  6
1  20000        2  2  2