我有数据框
C1 c10 val val_type
1 3 5 target
1 3 8 end
1 3 9 other
2 8 1 end
2 8 2 target
2 8 9 other
C1、C10 的值创建 3 个组。在这些组中,我想创建一个新的目标/结束列。所以输出将是:
C1 c10 val val_type new
1 3 5 target 0.652
1 3 8 end 0.652
1 3 9 other 0.652
2 8 12 end 0.166
2 8 2 target 0.166
2 8 9 other 0.166
这样做的最佳方法是什么?
编辑:忽略其他
我们可以pivot
对数据框进行整形,然后使用eval
计算target / end
,然后使用评估列merge
给出df
C1, c10
c = ['C1', 'c10']
df.merge(df.pivot(c, 'val_type', 'val').eval('target/end').rename('new'), on=c)
C1 c10 val val_type new
0 1 3 5 target 0.625000
1 1 3 8 end 0.625000
2 1 3 9 other 0.625000
3 2 8 12 end 0.166667
4 2 8 2 target 0.166667
5 2 8 9 other 0.166667
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句