首页 > 解决方案 > 数据框中的计算

问题描述

所以我有以下计算:

test["calculation"] = 0.16667*10**((test["Temp"][1:]-121.1)/10).reset_index(drop=True)

但我想在这个公式中添加一个 if else

如果“温度”>= 91.11,则必须使用该公式。如果“温度”低于 91.11,则结果必须为 0。

这是我目前使用公式的结果:

    Temp    calculation
0   90.01   0.000164
1   91.03   0.000415
2   95.06   0.001315
3   100.07  0.002896
4   103.50  NaN

所以对于 90.01 温度。计算为 0。

编辑:我想要公式的 ifelse。因此,当“温度”<91.11 时,计算结果为 0。当“温度”>= 91.11 时,结果必须是公式。

例如,这将是结果:

    Temp    calculation
0   90.01   0
1   91.03   0
2   95.06   0.001315
3   100.07  0.002896
4   103.50  NaN

标签: pythonpandas

解决方案


使用Series.shift并删除reset_index

test["calculation"] = 0.16667*10**((test["Temp"].shift(-1)-121.1)/10)
print (test)
     Temp  calculation
0   90.01     0.000164
1   91.03     0.000415
2   95.06     0.001315
3  100.07     0.002896
4  103.50          NaN

编辑:您可以通过添加掩码numpy.where

test["calculation"] = np.where(test["Temp"]<91.11, 
                               0, 
                               0.16667*10**((test["Temp"].shift(-1)-121.1)/10))
print (test)
     Temp  calculation
0   90.01     0.000000
1   91.03     0.000000
2   95.06     0.001315
3  100.07     0.002896
4  103.50          NaN

推荐阅读