我有DF:
Col1 Col2 Label
0 0 5345
1 0 7574
2 0 3445
0 1 2126
1 1 4653
2 1 9566
所以我试图在Col1和Col2上进行分组,以基于Label列获取索引值,如下所示:
df_gb = df.groupby(['Col1','Col2'])['Label'].agg(['sum', 'count'])
df_gb['sum_count'] = df_gb['sum'] / df_gb['count']
sum_count_total = df_gb['sum_count'].sum()
index = df_gb['sum_count'] / 10
Col2 Col1
0 0 2.996036
1 3.030063
2 3.038579
1 0 2.925314
1 2.951295
2 2.956083
2 0 2.875549
1 2.899254
2 2.905063
到目前为止,一切都如我所料。但是现在我想根据这两个groupby列将此“索引” groupby df分配给我的原始“ df”。如果只有一列,则使用map()函数,但如果我想基于两列顺序分配索引值,则不会。
df_index = df.copy()
df_index['index'] = df.groupby([]).apply(index)
TypeError: 'Series' objects are mutable, thus they cannot be hashed
尝试了agg()和transform(),但没有成功。任何想法如何进行?
提前致谢。布里斯托
我相信您需要join
:
a = df.join(index.rename('new'), on=['Col1','Col2'])
print (a)
Col1 Col2 Label new
0 0 0 5345 534.5
1 1 0 7574 757.4
2 2 0 3445 344.5
3 0 1 2126 212.6
4 1 1 4653 465.3
5 2 1 9566 956.6
df['new']=df.groupby(['Col1','Col2'])['Label'].transform(lambda x: x.sum() / x.count()) / 10
print (df)
Col1 Col2 Label new
0 0 0 5345 534.5
1 1 0 7574 757.4
2 2 0 3445 344.5
3 0 1 2126 212.6
4 1 1 4653 465.3
5 2 1 9566 956.6
如果没有NaN
S中Label
从柱使用的解决方案零的建议,谢谢:
df.groupby(['Col1','Col2'])['Label'].transform('mean') / 10
如果需要NaN
通过count
使用解决方案仅计算非s值transform
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句