我有一个数据帧:
Name Segment Axis 1 2 3 4 5
0 Amazon 1 slope NaN 100 120 127 140
1 Amazon 1 x 0.0 1.0 2.0 3.0 4.0
2 Amazon 1 y 0.0 0.4 0.8 1.2 1.6
3 Amazon 2 slope NaN 50 57 58 59
4 Amazon 2 x 0.0 2.0 4.0 6.0 8.0
5 Amazon 2 y 0.0 1.0 2.0 3.0 4.0
df2:
Name Segment Optimal Cost
Amazon 1 115
Amazon 2 60
Netflix 1 100
Netflix 2 110
我试图将轴列中的坡度值与相应的最佳成本值进行比较,并提取坡度、x和y值
规则是:找到最后一个坡度值大于其相应的最佳成本
如果没有大于最佳成本的值,则报告斜率为零的位置
如果只有大于最佳成本的值,则报告最高y值
预期产出:
Name Segment slope x y
0 Amazon 1 120 2 0.8
1 Amazon 2 NaN 0 0
在@wwnde的帮助下。当前代码为
s=df.set_index(['Name' , 'Segment','Axis']).stack().unstack('Axis')
s=s.dropna(subset=["slope"]).sort_values("slope").reset_index(level=2, drop=True)
df3=pd.merge(s, df2, on=['Name', 'Segment'], how='left')
df3[df3['slope']>df3['Optimal_Cost']].groupby(['Name',
'Segment']).first().reset_index()
但是,只有当它发现最后一个斜率值大于其相应的最佳成本时,才会返回值
让我们继续使用@wwnde解决方案,并对其进行一些更改:
out
的输出:相关问题 更多 >
编程相关推荐