简体   繁体   English

熊猫groupby在行条件

[英]pandas groupby on row condition

i have a sample data set: 我有一个样本数据集:

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) 

it looks like: 看起来像:

    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

i want to apply groupby to rows that are not measure=3 by 'H#' and 'measure' to sum up 'D' and 'N'. 我想对不按“ H#”和“ measure” 度量= 3的行应用groupby,以总结“ D”和“ N”。 desired output: 所需的输出:

    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

my attempt: 我的尝试:

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

the syntax for the last line of code is wrong, how can i apply groupby to the masked dataset? 最后一行代码的语法错误,如何将groupby应用于屏蔽的数据集?

IIUC: IIUC:

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

You can use break up your df and group then concatenate back: 您可以使用分解您的df和组,然后串联起来:

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

Output: 输出:

      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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM