如何从groupby操作中排除行



我正在使用attribute列进行groupby操作,但我想排除将用于计算每个属性内的总折扣的desc_type 1 and 2

pd.DataFrame({'ID':[10,10,10,20,30,30],'attribute':['attrib_1','desc_type1','desc_type2','attrib_1','attrib_2','desc_type1'],'value':[100,0,0,100,30,0],'discount':[0,6,2,0,0,13.3]})

输出:

ID       attribute       value      discount
10       attrib_1        100          0
10       desc_type1       0           6
10       desc_type2       0           2
20       attrib_1         100         0
30       attrib_2         30          0
30       desc_type1       0           13.3

我想按attribute对此数据帧进行分组,但不包括desc_type1 and desc_type2

所需输出:

attribute     ID_count    value_sum   discount_sum
attrib_1         2          200          8
attrib_2         1          30          13.3

解释:

attrib_1具有discount_sum=8,因为属于attrib_1ID 30具有两个desc_type

attrib_2具有discount_sum=13.3,因为ID 10具有一个desc_type

ID=20没有折扣类型。

到目前为止我做了什么:

df.groupby('attribute').agg({'ID':'count','value':'sum','discount':'sum'})

但上面的行并没有将desc_type 1 and 2从分组中排除

重要提示:身份证可能有折扣或没有折扣。

realdataset链接:realdataset

您可以根据ID填充属性,然后groupby.agg:

m = df['attribute'].str.startswith('desc_type')
group = df['attribute'].mask(m).groupby(df['ID']).ffill()
out = (df
.groupby(group, as_index=False)
.agg(**{'ID_count': ('ID', 'nunique'),
'value_sum': ('value', 'sum'),
'discount_sum': ('discount', 'sum')
})
)

输出:

ID_count  value_sum  discount_sum
0         2        200           8.0
1         1         30          13.3

你好,我认为这有帮助:

df.loc[(df['attribute'] != 'desc_type1') &( df['attribute'] != 'desc_type2')].groupby('attribute').agg({'ID':'count','value':'sum','discount':'sum'})

输出:

ID  value   discount
attribute           
attrib_1    2   200 0.0
attrib_2    1   30  0.0

最新更新